import csv
article = input()
# 统计每个单词出现的次数
word_count = {}
words = article.lower().split()
for word in words:
# 去除单词中的标点符号
word = word.strip(",.")
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# 按照出现次数降序排序
sorted_words = sorted(word_count.items(), key=lambda x: x[1], reverse=True)
# 写入前三个高频词语到CSV文件
with open('Pyprog0705.csv', 'w', newline='') as f:
header = ['单词,次数']
writer = csv.writer(f)
writer.writerow(header)
for word, count in sorted_words[:3]:
writer.writerow([word, count])
python实验7(5)统计文本词频
最新推荐文章于 2023-11-28 00:00:24 发布