首頁  >  文章  >  後端開發  >  如何使用 Counter 在 Python 中對詞頻進行計數和排序?

如何使用 Counter 在 Python 中對詞頻進行計數和排序?

Susan Sarandon
Susan Sarandon原創
2024-10-21 21:37:02466瀏覽

How to Count and Sort Word Frequencies in Python Using Counter?

統計和排序清單中的單字頻率

在最近的項目中,您遇到了一個問題,需要統計清單中單字的出現次數並對其進行排序按頻率排列,最常出現的單字位於清單的開頭。雖然您對該解決方案有了基本的了解,但不確定如何在 Python 3.3 中有效地實現它。

幸運的是,Python 的 collections.Counter 類別為這個問題提供了一個簡單而有效的解決方案。下面是一個範例:

<code class="python">from collections import Counter

# Create a list of words
list1 = ['apple', 'egg', 'apple', 'banana', 'egg', 'apple']

# Use Counter to count word occurrences
counts = Counter(list1)

# Print the counts
print(counts)  # Counter({'apple': 3, 'egg': 2, 'banana': 1})</code>

在此範例中,Counter 建立一個類似字典的對象,其中鍵是單詞,值是單字的計數。 print 語句輸出每個唯一單字的計數。

要依照頻率對單字排序,可以使用 Counter 的most_common() 方法。此方法傳回一個元組列表,其中每個元組包含一個單字及其計數。預設情況下,清單按頻率降序排序,這意味著最常見的單字將位於開頭。

以下是對單字清單進行排序的方法:

<code class="python"># Sort the words based on frequency
sorted_words = [word for word, count in sorted(counts.most_common(), key=lambda x: x[1], reverse=True)]

# Print the sorted list
print(sorted_words)  # ['apple', 'egg', 'banana']</code>

在此代碼,使用reverse = True參數按第二個元素(計數)按降序對元組列表進行排序。這可確保最常見的單字在排序單字清單中排在第一位。

以上是如何使用 Counter 在 Python 中對詞頻進行計數和排序?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn