Pythonで単語の数を数える方法は何ですか?

単語の数を数える方法は次の手順で行うことができます。

  1. テキストの内容を単語リストに分割します。
  2. 単語リストを巡回して、それぞれの単語の出現回数をカウントします。

以下是一个用于统计文本中单词数量的示例代码:

def count_words(text):
    # 将文本内容转换为小写,并去除标点符号
    text = text.lower()
    text = ''.join(e for e in text if e.isalnum() or e.isspace())
    
    # 分割文本内容为单词列表
    words = text.split()
    
    # 统计每个单词的出现次数
    word_count = {}
    for word in words:
        if word in word_count:
            word_count[word] += 1
        else:
            word_count[word] = 1
    
    return word_count

text = "Python is a popular programming language. Python is used in various fields including web development, data science, and machine learning."
result = count_words(text)
print(result)

上記のコードを実行すると、各単語とその出現回数が出力されます。

bannerAds