![](/img/trans.png)
[英]Python program for word count, average word length, word frequency and frequency of words starting with letters of the alphabet
[英]word frequency program in python
假設我有一個稱為單詞的單詞列表,即單詞= [“ 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)表示法是什么?
如果您有字典,則get()
是一種方法,其中w
是保存要查找的單詞的變量,而0
是默認值。 如果字典中不存在w
,則get
返回0
。
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})
如果鍵不存在,則字典的get()
方法允許使用默認值作為第二個參數。 所以counts.get(w,0)
給你0
,如果w
中不存在counts
。
字典上的get
方法返回存儲在鍵中的值,或者返回由可選的第二個參數指定的默認值。 在您的情況下,您告訴它“如果該鍵尚未在字典中,則檢索0作為先前的計數,然后將其添加到該值並將其放在字典中。”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.