Skip to main content
 首页 » 编程设计

python之python中的词频程序

2025年05月04日9tintown

假设我有一个名为 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) 符号是什么意思?

请您参考如下方法:

如果你有一本字典,get() 是一种方法,其中 w 是一个变量,其中包含你正在查找的单词和 0 是默认值。如果 w 不在字典中,get 返回 0。