我無法從文件中讀取內容並將其作爲字典返回。每個文件都包含以\ n分隔的數字,目標是計算將每個數字作爲關鍵字返回的數字,關鍵字的值是文件中的次數。Python - 從文件中獲取數字列表並返回字典表示形式
例如:當filea.txt
包含 "1\n1\n1\n2\n3\n3\n3\n3\n5\n"
函數應該返回 {1:3,2:1,3:4,5:1}
時filea.txt
包含"100\n100\n3\n100\n9\n9\n"
函數應該返回{100:3, 3:1, 9:2}
時fileb.txt
包含"13\n13\n13\n13\n13\n13\n13\n13\n"
函數應該返回{13:8}
這裏是我當前的嘗試:
def file_counts(filename):
a = open('filea.txt')
b = open('fileb.txt')
info = a.read()
info2 = b.read()
a.close()
b.close()
if info == True:
return (dict(collections.Counter(info)))
elif info2 == True:
return (dict(collections.Counter(info2)))
else:
return None
目前這給我的錯誤沒有這樣的文件或目錄,我相信這是因爲文件的內容在不同的測試用例中更改。所以filea可以包含不同的信息,並且該功能需要對此進行解釋。由於任何人誰幫助
感謝您解釋爲什麼我的代碼除了您的代碼不工作這個解決方案真的很有用 – n00bprogrammer22