2017-10-04 81 views
-1

我正在編寫一個代碼,需要用戶輸入並計算一個單詞出現的次數。我需要使用字典,因爲這是一個學校作業。如何將單詞和值添加到字典中?

,如果我有用戶輸入類似:

"a turtle on a fence had help" 

那麼輸出將是:

{'a': 2, 'turtle': 1, 'on': 1, 'fence': 1, 'had': 1, 'help': 1} 

我知道我需要將單詞添加到字典中,如果它不在那裏首先要做出值1.我也知道,如果它在那裏,我需要在它出現後每次增加1。我只是不完全確定如何執行該過程。

+0

你嘗試過什麼嗎? – grubjesic

+0

我可能會拆分字符串,然後遍歷它並檢查單詞/字母是否已經在字典中。如果它是+ = 1,如果不是,則創建一個新的字典項目。 – kstullich

+0

這可能會幫助你,[工作字典](https://stackoverflow.com/questions/13003575/how-to-add-words-from-a-text-file-to-a-dictionary-depending-on-名字) – Dharmesh

回答

1
>>> sentence = 'a turtle on a fence had help' 
>>> output = {} 
>>> for word in sentence.split(): 
...  if word not in output.keys(): 
...    output[word] = 0 
...  output[word] += 1 
... 
>>> print(output) 
{'a': 2, 'turtle': 1, 'help': 1, 'fence': 1, 'on': 1, 'had': 1} 
2

您可以在Counter看看:

from collections import Counter 

c = "a turtle on a fence had help" 

dict(Counter(c.split())) 

輸出:

{'a': 2, 'fence': 1, 'had': 1, 'help': 1, 'on': 1, 'turtle': 1} 

你需要將它拆分的 「」,因爲在Python中,字符串像imutable名單。意思是你可以像列表一樣訪問數據(c[0] -> "a"),但是在做c[0] = "p"時,會產生TypeError