python中的词频程序

发布于 2024-10-20 21:36:33 字数 367 浏览 2 评论 0原文

假设我有一个名为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.get(w,0) 到底做了什么?具体来说,(w,0) 符号是什么?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

滥情哥ㄟ 2024-10-27 21:36:33

如果您有字典,get() 是一种方法,其中 w 是保存您要查找的单词的变量,0 是默认值。如果字典中不存在 w,则 get 返回 0

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.

拥抱我好吗 2024-10-27 21:36:33

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})

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})
仅此而已 2024-10-27 21:36:33

如果键不存在,字典 get() 方法允许使用默认值作为第二个参数。因此,如果 w 不存在于 counts 中,counts.get(w,0) 将为您提供 0

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.

好倦 2024-10-27 21:36:33

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

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."

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文