在 Python 中找出資料集中的 k 個出現頻率最高的單詞


如果需要找出資料集中出現頻率最高的 10 個單詞,可以使用 collections 模組幫助我們找到。collections 模組有一個 counter 類,它會提供單詞列表中的單詞計數。我們還使用了 most_common 方法找出所需單詞的數量(如程式輸入中所述)。

示例

在下面的示例中,我們取一段文字,然後首先使用 split() 建立一個單詞列表。然後我們將應用 counter() 找出所有單詞的計數。最後,most_common 函式將為我們提供適當的結果,即出現頻率最高的前 n 個單詞。

from collections import Counter
word_set = " This is a series of strings to count " \
   "many words . They sometime hurt and words sometime inspire "\
   "Also sometime fewer words convey more meaning than a bag of words "\
   "Be careful what you speak or what you write or even what you think of. "\
# Create list of all the words in the string
word_list = word_set.split()

# Get the count of each word.
word_count = Counter(word_list)

# Use most_common() method from Counter subclass
print(word_count.most_common(3))

輸出

執行上述程式碼會向我們提供以下結果 −

[('words', 4), ('sometime', 3), ('what', 3)]

更新於: 07-08-2019

957 次瀏覽

開啟你的職業生涯

完成課程即可獲得認證

開始
廣告