1

假设我有一个名为 words 的单词列表,即 words = ["hello", "test", "string", "people", "hello", "hello"] 我想创建一个字典以获得词频.

假设字典被称为“计数”

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 回答 4

7

如果你有一本字典,get()是一种方法,其中w一个变量保存着你正在查找的单词,并且0是默认值。如果w字典中不存在,则get返回0.

于 2011-03-08T17:20:42.437 回答
6

FWIW,使用 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})
于 2011-03-08T18:53:57.670 回答
4

get()如果键不存在,字典方法允许将默认值作为第二个参数。所以counts.get(w,0)给你0如果w不存在于counts.

于 2011-03-08T17:20:10.280 回答
0

字典上的get方法返回存储在键中的值,或者可选的默认值,由可选的第二个参数指定。在您的情况下,您告诉它“如果该键尚未在字典中,则为先前的计数检索 0,然后将其添加到该值并将其放入字典中。”

于 2011-03-08T17:20:30.250 回答