2015-03-03 53 views
0

所以我是matplotlib的新手,我使用的是YouTube視頻並重新創建了它的代碼,看看它是否適合我。代碼如下,從matplotlib中的文件做練習抓取信息

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' 

我不知道我在做什麼錯的,什麼這個錯誤表示。任何幫助,將不勝感激。

+1

比較這些來自代碼的碎片:split('/ n')'和錯誤:''5 \ n2'' – cphlewis 2015-03-03 08:16:32

回答

0

,所以我想通了,發生了什麼事,有一些空行的數據的末尾,我不得不做出修改的xAndY

for plotpair in sepFile: 
xandy = plotpair.split(',') 
if len(xandy)>1: 
    x.append(int(float(xandy[0]))) 
    y.append(int(float(xandy[1]))) 

的LEN這花了照顧的問題

0

你犯了一個很容易被忽略的錯誤,錯誤地認爲是\/字符。文件閱讀行應該看起來像sepFile = readFile.read().split('\n'),因爲它是\n而不是/n,它結束了一行。