编写程序,统计文件“Nixon.txt”中出现频率最高的20个单词,并将统计结果写入“Tongji.txt”文件中。 (注意:除去the',and',to',of,a,be,from'in'for等无意义的单词
时间: 2024-03-01 14:55:52 浏览: 24
下面是一个 Python 代码示例,用于统计文件中出现频率最高的20个单词,并将结果写入到另一个文件中:
```python
import re
from collections import Counter
# 定义无意义的单词列表
useless_words = ['the', 'and', 'to', 'of', 'a', 'be', 'from', 'in', 'for']
# 打开文件并读取内容
with open('Nixon.txt', 'r') as f:
content = f.read()
# 使用正则表达式分割字符串,并将所有单词转换为小写
words = re.findall('\w+', content.lower())
# 过滤掉无意义的单词并统计出现次数
word_counts = Counter(word for word in words if word not in useless_words)
# 获取出现频率最高的20个单词
top_words = word_counts.most_common(20)
# 将结果写入文件
with open('Tongji.txt', 'w') as f:
for word, count in top_words:
f.write(f"{word}: {count}\n")
```
在上面的代码中,我们首先定义了一个无意义的单词列表,然后打开文件并读取内容。使用正则表达式`\w+`将字符串分割成单词,并将所有单词转换为小写。使用列表推导式过滤掉无意义的单词,并使用`Counter`对象统计每个单词出现的次数。
然后,我们获取出现频率最高的20个单词,并将结果写入到文件中。在写入文件时,我们使用了`f-string`来格式化字符串,以便将单词和出现次数写入文件。