Pythonでテキストの単語の出現回数を数える方法は何ですか?
Pythonを使用してテキストの単語頻度を統計するには、次の手順を使用できます:
- テキストファイルを開いて、テキストの内容を読み込んでください。
with open("text.txt", "r") as file:
text = file.read()
- テキストを分割する。
import re
# 去除标点符号和空白字符
text = re.sub(r'[^\w\s]', '', text)
# 将文本拆分为单词列表
words = text.split()
- 各単語の出現回数を集計する。
from collections import Counter
word_count = Counter(words)
- 出現頻度をまとめ、結果を出力してください。
for word, count in word_count.most_common():
print(word, count)
以下は完璧なコードです:
import re
from collections import Counter
with open("text.txt", "r") as file:
text = file.read()
text = re.sub(r'[^\w\s]', '', text)
words = text.split()
word_count = Counter(words)
for word, count in word_count.most_common():
print(word, count)
実際のテキストファイルのパスに、コード中の”text.txt”を置き換えるようにしてください。