from collections import defaultdict
def count_word_frequencies(text):
## デフォルト値 0 の defaultdict を作成する
word_counts = defaultdict(int)
## テキストを単語に分割して小文字に変換する
words = text.lower().split()
## 各単語をクリーンアップし(句読点を削除し)出現回数をカウントする
for word in words:
## 一般的な句読点を削除する
clean_word = word.strip('.,!?:;()"\'')
if clean_word: ## 空の文字列をスキップする
word_counts[clean_word] += 1
return word_counts
## サンプルテキストで関数をテストする
sample_text = """
Python is amazing! Python is easy to learn, and Python is very powerful.
With Python, you can create web applications, analyze data, build games,
and automate tasks. Python's syntax is clear and readable.
"""
word_frequencies = count_word_frequencies(sample_text)
## 結果を表示する
print("単語頻度:")
for word, count in sorted(word_frequencies.items()):
print(f" {word}: {count}")
## 最も頻出する単語を見つける
print("\n最も頻出する単語:")
sorted_words = sorted(word_frequencies.items(), key=lambda x: x[1], reverse=True)
for word, count in sorted_words[:5]: ## 上位 5 つの単語
print(f" {word}: {count}")