所以我想寫一段代碼從文件中取文本,移入字典,然後處理它。我不斷收到此錯誤:文件到字典,不能讓程序運行
File "C:\Users\Oghosa\Assignment2.py", line 12, in <module>
builtins.IndexError: string index out of range
這是我的計劃:
endofprogram = False
dic = {}
try:
filename = input("Please Enter the Filename:")
infile = open(filename, 'r')
except IOError:
print("Error Reading File! Program ends here!")
endofprogram = True
if endofprogram == False:
for line in infile:
line = line.strip("\n")
if (line != " ") and (line[0] != "#"):
item = line.split(":")
print(items)
dic["Animal id"] = item[0]
dic["Date"] = item[1]
dic["Station"] = item[2]
print(dic)
可以指出我的錯誤,請人援助?
以下是樣本輸入文本:
#Comments
a01:01-24-2011:s1
a03:01-24-2011:s2
<blank line>
<blank line>
a02:01-24-2011:s2
a03:02-02-2011:s2
a03:03-02-2011:s1
a02:04-19-2011:s2
<blank line>
#comments
a01:05-14-2011:s2
a02:06-11-2011:s2
a03:07-12-2011:s1
a01:08-19-2011:s1
a03:09-19-2011:s1
a03:10-19-2011:s2
a03:11-19-2011:s1
a03:12-19-2011:s2
你能給我們一個輸入文件樣本嗎? – Christian
@Christian這裏有一個叫animallog.txt – user2767528
不要把它作爲評論發佈,編輯你的帖子並把它放在那裏。確保格式正確。 – Christian