要找出文本文件中出现频率最高的单词,我们可以采用以下步骤:
import re
from collections import Counter
def find_most_common_word(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
text = file.read().lower() # 转换为小写以统一单词
words = re.findall(r'\b\w+\b', text) # 使用正则表达式提取单词
word_counts = Counter(words)
most_common_word, frequency = word_counts.most_common(1)[0]
return most_common_word, frequency
# 使用示例
file_path = 'example.txt'
word, freq = find_most_common_word(file_path)
print(f"出现频率最高的单词是 '{word}',共出现了 {freq} 次。")
utf-8
。通过上述方法和代码示例,你可以有效地找出文本文件中出现频率最高的单词,并解决在实际操作中可能遇到的问题。
领取专属 10元无门槛券
手把手带您无忧上云