ホームページ  >  記事  >  バックエンド開発  >  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

単語の頻度を数え、出現順に並べ替える

あなたが述べたように、あなたの目標は 2 つのリストを確立することです。1 つは個別の単語用で、もう 1 つは単語用です。それぞれの頻度。単語は頻度の昇順に並べられています。アプローチの概要は説明しましたが、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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。