我不明白为什么列表索引超出范围。因为当我分割文件'very_short.csv'时,它分为三部分。例如,它分手机场,2007,175702。机场是文本[0],2007年是文本[1],175702是文本[2]。所以当我调用newYearCount = createYearCount(int(text [1]),int(text [2]))时,它是如何超出范围的?
这是我得到的错误......
>>> import wordData
>>> words = wordData.readWordFile('very_short.csv')
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
words = wordData.readWordFile('very_short.csv')
File "/Users/lol/Desktop/lol's Windows/CS/CS1/hw/uni/wordData.py", line 31, in readWordFile
newYearCount = createYearCount(int(text[1]), int(text[2]))
IndexError: list index out of range
class YearCount(rit_object):
__slots__ = ('year', 'count')
_types = (int , int )
def createYearCount(year, count):
return YearCount(year, count)
def readWordFile(fileName):
result = {}
for line in fileName:
text = line.split(',')
wordy = text[0]
print(text)
if len(text) > 1:
newYearCount = createYearCount(int(text[1]), int(text[2]))
if line not in result:
result[wordy] = [newYearCount]
else:
result[wordy].append(newYearCount)
else:
return ''
return result
def main():
fileName = input('Enter filename: ')
print(readWordFile(open(fileName)))
main()
这就是我的very_short.csv文件中的内容:
airport, 2007, 175702
airport, 2008, 173294
request, 2005, 646179
request, 2006, 677820
request, 2007, 697645
request, 2008, 795265
wandered, 2005, 83769
wandered, 2006, 87688
wandered, 2007, 108634
wandered, 2008, 171015
感谢。
编辑:
Enter filename: very_short.csv
['airport', ' 2007', ' 175702\n']
['airport', ' 2008', ' 173294\n']
['request', ' 2005', ' 646179\n']
['request', ' 2006', ' 677820\n']
['request', ' 2007', ' 697645\n']
['request', ' 2008', ' 795265\n']
['wandered', ' 2005', ' 83769\n']
['wandered', ' 2006', ' 87688\n']
['wandered', ' 2007', ' 108634\n']
['wandered', ' 2008', ' 171015\n']
{'request': [YearCount( year=2008, count=795265 )], 'airport': [YearCount( year=2008, count=173294 )], 'wandered': [YearCount( year=2008, count=171015 )]}
Enter a word to calculate the count: airport
['v']
0
答案 0 :(得分:0)
尝试在字符串之前打印text
,这会给您带来错误。最有可能的是,文件末尾有一个空行,它会拆分为单值列表。
而不是
newYearCount = createYearCount(int(text[1]), int(text[2]))
使用
if len(text)>1:
newYearCount = createYearCount(int(text[1]), int(text[2]))
if line not in result:
result[word] = [newYearCount]
else:
result[word].append(newYearCount)
else:
return ''