我正在讀取並打印出.CSV文件中的文本。我正在努力讓它工作。任何幫助都會很棒。未使用csv模塊和defaultdict的Python錯誤輸出
def readWordFile(fileName):
for line in fileName:
text = line.split(', ')
word = text[0]
newYearCount = createYearCount(int(text[1]), int(text[2]))
result = {}
if line not in result:
result[word] = [newYearCount]
else:
result[word].append(newYearCount)
print(result)
def main():
fileName = input('Enter filename: ')
readWordFile(open(fileName))
main()
我有代表一個字,年份和該單詞的在這一年出現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
我現在readWordFile功能輸出看起來像:
{'airport': [YearCount(year=2007, count=175702)]}
{'airport': [YearCount(year=2008, count=173294)]}
{'request': [YearCount(year=2005, count=646179)]}
{'request': [YearCount(year=2006, count=677820)]}
{'request': [YearCount(year=2007, count=697645)]}
{'request': [YearCount(year=2008, count=795265)]}
{'wandered': [YearCount(year=2005, count=83769)]}
{'wandered': [YearCount(year=2006, count=87688)]}
{'wandered': [YearCount(year=2007, count=108634)]}
{'wandered': [YearCount(year=2008, count=171015)]}
我想要做的是試圖打印正確的輸出,請看下面。
{
’airport’: [
YearCount(year=2007, count=175702),
YearCount(year=2008, count=173294)
],
’wandered’: [
YearCount(year=2005, count=83769),
YearCount(year=2006, count=87688),
YearCount(year=2007, count=108634),
YearCount(year=2008, count=171015)
],
’request’: [
YearCount(year=2005, count=646179),
YearCount(year=2006, count=677820),
YearCount(year=2007, count=697645),
YearCount(year=2008, count=795265)
]
}
謝謝。
您應該使用[csv](https://docs.python.org/2/library/csv.html)標準模塊和defaultdict。 – 2014-11-22 00:45:19
如果你有一個新的問題,問一個[*新問題*](http://stackoverflow.com/questions/ask)(或更好,但搜索的答案,因爲我敢肯定,它已經回答過)。不要編輯這個問題完全成爲一個新問題 - 只會使現有的答案對新問題無效,而且整個問題對未來的訪問者會變得混亂和無用。 – 2014-11-22 01:47:07