【问题标题】:Invalid Literal for int() with base 10: "以 10 为底的 int() 的无效文字:"
【发布时间】:2014-03-18 20:44:30
【问题描述】:

我有来自加速度计 (x, y, z) 的一串数据(在文本文件“XXX XXX XXX”中看起来像这样,我正在尝试读取它并转换为包含三个数据子图的折线图。我正在修改朋友的一些代码来执行此操作,但我不确定其中一些错误来自哪里。显然是初学者程序员。非常感谢帮助。

错误:int() 以 10 为底的无效文字

import os
import numpy as npy
import matplotlib.pyplot as plt
global y0,y1,y2
increment_size = 8000
datasample_size = 16000

from os.path import join
filepath = "C:\\Users\\Riley\\Documents\\Programming\\"
infile = join(filepath, 'data.txt')
infile = open(infile,"r")
singleline = infile.readline()
asciidata = singleline.split()
asciidata[0]=asciidata[0][3:]  
y0=[int(asciidata[0])]
y1=[int(asciidata[1])]
y2=[int(asciidata[2])]

count = 0
for singleline in infile:
    count += 1
    if (count % 10000) == 0:
        print(count) 
    asciidata = singleline.split()
    y0.append(int(asciidata[0]))
    y1.append(int(asciidata[1]))
    y2.append(int(asciidata[2]))
infile.close()
totaldata=count-1
print(totaldata)

low = 0
high = datasample_size


while low < totaldata:

    t = npy.arange(low,high)

    plt.subplot(311)
    plt.ylim(-2000,2000)
    plt.plot(t,y0[low:high])

    plt.subplot(312)
    plt.ylim(-2000,2000)
    plt.plot(t,y1[low:high])

    plt.subplot(313)
    plt.ylim(-2000,2000)
    plt.plot(t,y2[low:high])

    outfilename = filepath + 'Plots/' + shortfilename + '_' + str(low) + '.png'
    plt.savefig(outfilename)

    outfilename2 = filepath + 'Datasegments/' + shortfilename + '_' + str(low) + '.txt'
    outfile = open(outfilename2,"w")
    for j in range(low,high):
        outfile.write(str(y0[j])+'\t'+str(y1[j])+'\t'+str(y2[j])+'\n')

#    print(low),

    plt.show()


    low = low + increment_size
    high = high + increment_size
    if high > totaldata:
        high = totaldata

#    if low > 10000:
#        break

# plt.close()

【问题讨论】:

    标签: python text matplotlib


    【解决方案1】:

    您可能试图用int() 解析float()

    如果您需要处理空值,请尝试int(s or 0)

    【讨论】:

      【解决方案2】:

      有一个 numpy 函数可以为您完成几乎所有这些工作。在不知道你的数据文件格式的情况下我很难测试它(如果你粘贴在'data.txt'的前几行会有所帮助)

      from os import path
      
      import numpy as npy
      import matplotlib.pyplot as plt
      
      increment_size  =  8000
      datasample_size = 16000
      
      filepath = "C:\\Users\\Riley\\Documents\\Programming\\"
      infile = path.join(filepath, 'data.txt')
      
      # This line replaces all the file reading lines:
      y0, y1, y2 = npy.genfromtxt(infile, unpack=True)
      
      totaldata = len(y0)
      print(totaldata)
      
      low = 0
      high = datasample_size
      
      while low < totaldata:
          ...
      

      可能绘图也可以更简单地完成,但我不确定我是否理解您为什么要逐节绘制它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-09-09
        • 2020-01-04
        • 2010-12-22
        • 2011-07-07
        • 2019-10-14
        相关资源
        最近更新 更多