Python中的词频程序
假设我有一个单词列表,叫做 words,比如说 words = ["hello", "test", "string", "people", "hello", "hello"],我想创建一个字典来统计每个单词出现的频率。
我们把这个字典叫做 'counts'。
counts = {}
for w in words:
counts[w] = counts.get(w,0) + 1
我不太明白的地方是 counts.get(w, 0)。书上说,通常你会用 counts[w] = counts[w] + 1 来增加单词的计数,但第一次遇到一个新单词时,它在 counts 里是找不到的,这样就会报错。这个说法没问题,但 counts.get(w, 0) 到底是干嘛的呢?特别是 (w, 0) 这个写法是什么意思?
4 个回答
4
字典的 get()
方法可以接受一个默认值作为第二个参数,如果你查找的键不存在的话。所以 counts.get(w,0)
的意思是,如果 w
在 counts
里找不到,就返回 0
。
6
如果你使用的是Python 2.7或更高版本,可能会更喜欢用collections.Counter
这个工具来处理数据,比如:
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})
7
如果你有一个字典,get()
是一个方法,其中 w
是一个变量,里面存着你想查找的单词,而 0
是默认值。如果字典里没有 w
这个单词,get
就会返回 0
。