首頁  >  文章  >  後端開發  >  如何使用 Python 3.3 計算詞頻並依出現次數排序

如何使用 Python 3.3 計算詞頻並依出現次數排序

Barbara Streisand
Barbara Streisand原創
2024-10-21 21:40:03837瀏覽

How to Count Word Frequencies and Sort by Occurrence Using Python 3.3

計算單字頻率並按出現次數排序

正如您所提到的,您的目標是建立兩個清單:一個用於不同的單字,另一個用於不同的單字它們各自的頻率,單字按頻率升序排列。您已經提供了該方法的概要,但讓我們使用 Python 3.3 填寫詳細資訊。

由於 Python 3.3 不包含計數器或字典等內建機制,因此我們將使用一個簡單的循環來達到期望的結果。

<code class="python"># Create lists to store unique words and their counts
unique_words = []
frequencies = []

# Iterate over the original list of words
for word in original_list:
    # Check if the word is already in the unique words list
    if word not in unique_words:
        # If not, add the word to the unique words list and initialize its frequency to 1
        unique_words.append(word)
        frequencies.append(1)
    else:
        # If the word is already in the list, increment its frequency
        frequencies[unique_words.index(word)] += 1

# Sort the unique word list based on the frequencies list
sorted_words = [word for _, word in sorted(zip(frequencies, unique_words), reverse=True)]

# Output the sorted list of unique words
print(sorted_words)</code>

此程式碼有效地計算單字頻率並對唯一單字進行相應排序,以唯一單字的排序清單形式提供輸出。

以上是如何使用 Python 3.3 計算詞頻並依出現次數排序的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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