2016-11-07 53 views
0

我無法從文件中讀取內容並將其作爲字典返回。每個文件都包含以\ 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可以包含不同的信息,並且該功能需要對此進行解釋。由於任何人誰幫助

回答

1

像這樣的東西應該就足夠了。請記住,沒有進行驗證。例如,空行,非數字字符。在你的問題看起來好像數字應該被轉換爲一個整數,但你的代碼沒有,所以我反正包括它。

from collections import Counter 

def file_counts(filename): 
    # Open file for reading 
    with open(filename, 'r') as file: 
     data = [] 
     # Go through each line of the file 
     for line in file: 
      value = int(line) 
      data.append(value) 

     return dict(Counter(data)) 

if __name__ == '__main__': 
    filename = 'testfile.txt' 
    print(file_counts(filename)) 

您曾經遇到過的問題。

def file_counts(filename): 
    a = open('filea.txt') 
    b = open('fileb.txt') 

您正在閱讀兩個文件並忽略作爲參數給出的文件名。

info = a.read() 

這將在整個文件中讀取,對於大型文件通常不是最好的。

if info == True: 

info將永遠True,因爲它是一個字符串。

return (dict(collections.Counter(info))) 

這是因爲它仍然是一個字符串通常正常,但是你沒有格式化的信息,所以你的字典包括\n字符,它不超過1個字符位數工作,因爲它每次計數個性。

你很可能會得到一個IOError。如果您只想使用文件名,則需要將文本文件放在與python文件相同的目錄中,否則您必須提供文件路徑

+0

感謝您解釋爲什麼我的代碼除了您的代碼不工作這個解決方案真的很有用 – n00bprogrammer22

0

從你的說法,我認爲你收到了IOError如:

IOError: [Errno 2] No such file or directory: 'filea.txt' 

如果您收到此錯誤,這是因爲open無法找到匹配當前工作目錄中的文件您要求它提取的文件名。您需要將路徑添加到文件名的開頭,例如/home/username/project/filea.txt以確保python正在正確的目錄中搜索。

一旦你能夠打開你的文件,並通過IOError,你的代碼有幾個扭結。

首先,讓我們來看看dict(collections.Counter(info))

>>> info = "100\n100\n3\n100\n9\n9\n" 
>>> dict(collections.Counter(info)) 
{'1': 3, '0': 6, '3': 1, '\n': 6, '9': 2} 

正如我們所看到的,是collections.Counter()解析字符串中的每個字符和計數每一個的發生。因此,「1」,「0」和「3」分別計數三次而不是三次計數100次。相反,你可以做如下的值的列表:

>>> info = info.strip()  # removes the last \n on the right 
>>> nums = info.split('\n') # breaks up the string into a list of elements 
>>> print(nums) 
['100', '100', '3', '100', '9', '9'] 
>>> print(dict(collections.Counter(nums))) 
{'9': 2, '100': 3, '3': 1} 

你還有關於你輸入一些錯誤,並在結束時,如果再聲明,但我會讓你先刺他們。 GL!