python 打开一篇中文文章,在该文章中找出使用频率最高的5个词语,然后对文章中所有出现的5个高频词语分别用" AA "、" BB "、" CC "、" DD "和" EE "替换,再存盘。
时间: 2023-07-05 13:22:01 浏览: 40
好的,我可以帮你写一个Python程序来完成这个任务。你需要先安装中文分词库 jieba。
以下是程序代码:
```python
import jieba
# 打开文件
with open('input.txt', 'r', encoding='utf-8') as f:
content = f.read()
# 分词
words_lst = jieba.lcut(content)
# 统计词频
word_count = {}
for word in words_lst:
if len(word) > 1:
word_count[word] = word_count.get(word, 0) + 1
# 排序
sorted_word = sorted(word_count.items(), key=lambda x: x[1], reverse=True)
# 找出频率最高的5个词
top_5_words = [w[0] for w in sorted_word[:5]]
# 替换高频词
for i in range(len(words_lst)):
if words_lst[i] in top_5_words:
words_lst[i] = {
top_5_words[0]: "AA",
top_5_words[1]: "BB",
top_5_words[2]: "CC",
top_5_words[3]: "DD",
top_5_words[4]: "EE"
}[words_lst[i]]
# 存盘
with open('output.txt', 'w', encoding='utf-8') as f:
f.write(" ".join(words_lst))
```
你需要将原始文章保存为 `input.txt` 文件,然后运行上述代码即可。程序会将高频词语替换为 `AA`、`BB`、`CC`、`DD` 和 `EE`,并将结果保存到 `output.txt` 文件中。