word frequency program in python

三世轮回 提交于 2021-02-18 19:07:10

问题


Say I have a list of words called words i.e. words = ["hello", "test", "string", "people", "hello", "hello"] and I want to create a dictionary in order to get word frequency.

Let's say the dictionary is called 'counts'

counts = {}
for w in words:
    counts[w] = counts.get(w,0) + 1

The only part of this I don't really understand is the counts.get(w.0). The book says, normally you would use counts[w] = counts[w] + 1 but the first time you encounter a new word, it won't be in counts and so it would return a runtime error. That all fine and dandy but what exactly does counts.get(w,0) do? Specifically, what's the (w,0) notation all about?


回答1:


If you have a dictionary, get() is a method where w is a variable holding the word you're looking up and 0 is the default value. If w is not present in the dictionary, get returns 0.




回答2:


FWIW, with Python 2.7 and above you may prefer to operate with collections.Counter, like:

In []: from collections import Counter
In []: c= Counter(["hello", "test", "string", "people", "hello", "hello"])
In []: c
Out[]: Counter({'hello': 3, 'test': 1, 'people': 1, 'string': 1})



回答3:


The dictionary get() method allows for a default as the second argument, if the key doesn't exist. So counts.get(w,0) gives you 0 if w doesn't exist in counts.




回答4:


The get method on a dictionary returns the value stored in a key, or optionally, a default value, specified by the optional second parameter. In your case, you tell it "Retrieve 0 for the prior count if this key isn't already in the dictionary, then add one to that value and place it in the dictionary."



来源:https://stackoverflow.com/questions/5235916/word-frequency-program-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!