在 matplotlib 中练习从文件中获取信息
Doing a practice grabbing info from a file in matplotlib
所以我是 matplotlib 的新手,我正在使用一个 youtube 视频并重新创建它的代码,看看它是否适合我。代码如下,
import numpy as np
import matplotlib.pyplot as plt
x=[]
y=[]
readFile = open('attempt2.txt', 'r')
sepFile= readFile.read().split('/n')
readFile.close()
for batman in sepFile:
xAndy = batman.split(',')
x.append(int(xAndy[0]))
y.append(int(xAndy[1]))
print x
print y
plt.plot(x,y)
plt.title('attempt 2')
plt.xlabel('attempt 2 x')
plt.ylabel('attempt 2 y')
plt.show()
当我运行这个代码时,错误说:
Traceback (most recent call last):
File "attempt_2.py", line 13, in <module>
y.append(int(xAndy[1]))
ValueError: invalid literal for int() with base 10: '5\n2'
我不确定我做错了什么以及这个错误意味着什么。任何帮助将不胜感激。
您犯了一个非常容易被忽视的错误,即弄错了 \
和 /
字符。文件读取行应该看起来像 sepFile = readFile.read().split('\n')
,因为它是 \n
而不是 /n
结束一行。
所以我弄清楚发生了什么,数据末尾有一些空行,我只需要修改 xAndY 的 len
for plotpair in sepFile:
xandy = plotpair.split(',')
if len(xandy)>1:
x.append(int(float(xandy[0])))
y.append(int(float(xandy[1])))
这解决了问题
所以我是 matplotlib 的新手,我正在使用一个 youtube 视频并重新创建它的代码,看看它是否适合我。代码如下,
import numpy as np
import matplotlib.pyplot as plt
x=[]
y=[]
readFile = open('attempt2.txt', 'r')
sepFile= readFile.read().split('/n')
readFile.close()
for batman in sepFile:
xAndy = batman.split(',')
x.append(int(xAndy[0]))
y.append(int(xAndy[1]))
print x
print y
plt.plot(x,y)
plt.title('attempt 2')
plt.xlabel('attempt 2 x')
plt.ylabel('attempt 2 y')
plt.show()
当我运行这个代码时,错误说:
Traceback (most recent call last):
File "attempt_2.py", line 13, in <module>
y.append(int(xAndy[1]))
ValueError: invalid literal for int() with base 10: '5\n2'
我不确定我做错了什么以及这个错误意味着什么。任何帮助将不胜感激。
您犯了一个非常容易被忽视的错误,即弄错了 \
和 /
字符。文件读取行应该看起来像 sepFile = readFile.read().split('\n')
,因为它是 \n
而不是 /n
结束一行。
所以我弄清楚发生了什么,数据末尾有一些空行,我只需要修改 xAndY 的 len
for plotpair in sepFile:
xandy = plotpair.split(',')
if len(xandy)>1:
x.append(int(float(xandy[0])))
y.append(int(float(xandy[1])))
这解决了问题