1

I'm trying to plot data from a textfile.

My data is in the form of:

2 - 5 6 6
4 - 5 6 7
6 - 5 6 3
8 - 5 6 3 
1 0 - 5 6 4 
1 2 - 5 6 4 
1 4 - 5 6 3

Here is my terminal report up to the error in question:

>>> from matplotlib import pyplot
>>> 
>>> time = []
>>> value = []
>>> 
>>> source = open("textfile6.txt", "r")
>>> 
>>> for line in source:
...     line.replace(' ', '')
...     t, v = line.split('-')
...     time.append(int(t))
...     value.append(int(v))
... 
'2-566\n'
Traceback (most recent call last):
  File "<stdin>", line 5, in <module>
ValueError: invalid literal for int() with base 10: '5 6 6\n'

So the rationale is that I use str.replace(' ', '') in order to strip the white spaces (str.strip() was not achieving this for some reason!). Then I str.split('-') to break up my columns.

However I keep getting:

ValueError: invalid literal for int() with base 10: '5 6 6\n'

..as if white spaces have magically appeared back in the second string.

4

2 回答 2

4

忽略.replace()了呼叫的输出:

line.replace(' ', '')

Python 字符串是不可变的,因此.replace()返回一个新的字符串值。重新绑定line到结果:

line = line.replace(' ', '')
于 2013-07-16T11:37:53.527 回答
0

或者,您可以将代码编写为:

import re

with open(inputfile) as fin:
    lines = (map(int, re.sub(r'[^\d-]', '', line).split('-')) for line in fin)
    time, value = zip(*lines)

print time, value
# (2, 4, 6, 8, 10, 12, 14) (566, 567, 563, 563, 564, 564, 563)

这样做的好处是在拆分的内容上更加明确,并一次性构建列表,而不是在每次迭代时追加。

于 2013-07-16T11:58:49.387 回答