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.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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您有字典,
get()
是一种方法,其中w
是保存您要查找的单词的变量,0
是默认值。如果字典中不存在w
,则get
返回0
。If you have a dictionary,
get()
is a method wherew
is a variable holding the word you're looking up and0
is the default value. Ifw
is not present in the dictionary,get
returns0
.FWIW,使用 Python 2.7 及更高版本,您可能更喜欢使用
collections.Counter
进行操作,例如:FWIW, with Python 2.7 and above you may prefer to operate with
collections.Counter
, like:如果键不存在,字典
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. Socounts.get(w,0)
gives you0
ifw
doesn't exist incounts
.字典上的 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."