2016-11-14 43 views
0

說我有一個文本文件,上面寫着:如何將文件讀入字典,其中鍵是單詞,值是Python中重複單詞的數量?

hello yellow apple yellow apple apple yellow.... 

我將如何改變這一個字典,以便它說的話,然後次數它重複:

{"hello": 1, "apple": 3, "yellow": 2} 

我是新來的Python並無法弄清楚這個問題,文本文件很大,所以我需要製作一個字典在多行。

+1

你能展示你的最佳嘗試,並解釋它有什麼問題? –

+0

[collections.Counter()](https://docs.python.org/2/library/collections.html#counter-objects) – furas

回答

1

像這樣的東西應該工作

letters = 'hello yellow apple yellow apple apple yellow' 
data = {} 
for word in letters.split(' '): 
    if word in data: 
     data[word] += 1 
    else: 
     data[word] = 1 

print(data) 

隨着輸出是

{'apple': 3, 'yellow': 3, 'hello': 1} 
0

File readingtext splitting,並且counting是,你應該在一些教程閱讀並第一次嘗試爲自己所有的概念之前只是要求解決方案。一旦你這樣做,你會發現這是解決這個簡潔的方式:

from collections import Counter 

with open('file.txt', 'r') as f: 
    c = Counter(f.read().split()) // c is a dict-like object holding the counts 
0
list_string="hello yellow apple yellow apple apple yellow".split(" ") 
results={} 
for i in list_string: 
    results[i]=list_string.count(i) if i not in results else results[i] 
print(results) 
0

如果您在字的文件正在看,這應該這樣做:

# Open your file of words and read it. 
with open('my_file', 'r') as f: 
    data = f.read() 

# Replace newline characters with spaces and remove any 
# spaces at the end of the string of words. 
data = data.replace('\n', ' ').rstrip() 

# Create a list out of the string, split on the space 
# character. 
words = data.split(' ') 

result = {} 
for w in words: 
    if w not in result: 
     result[w] = 1 
    else: 
     result[w] += 1 

print result 
相關問題