說我有一個文本文件,上面寫着:如何將文件讀入字典,其中鍵是單詞,值是Python中重複單詞的數量?
hello yellow apple yellow apple apple yellow....
我將如何改變這一個字典,以便它說的話,然後次數它重複:
{"hello": 1, "apple": 3, "yellow": 2}
我是新來的Python並無法弄清楚這個問題,文本文件很大,所以我需要製作一個字典在多行。
說我有一個文本文件,上面寫着:如何將文件讀入字典,其中鍵是單詞,值是Python中重複單詞的數量?
hello yellow apple yellow apple apple yellow....
我將如何改變這一個字典,以便它說的話,然後次數它重複:
{"hello": 1, "apple": 3, "yellow": 2}
我是新來的Python並無法弄清楚這個問題,文本文件很大,所以我需要製作一個字典在多行。
像這樣的東西應該工作
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}
File reading,text 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
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)
如果您在字的文件正在看,這應該這樣做:
# 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
你能展示你的最佳嘗試,並解釋它有什麼問題? –
[collections.Counter()](https://docs.python.org/2/library/collections.html#counter-objects) – furas