定义函数count_words(src_file) 统计源文件中英文单词出现的次数 定义函数sort_words(words, dest_file) 将统计结果以降序排列,并写入目标文件中 输入源文件s和目标文件名d 调用count_words(s),统计结果存于变量words中 调用函数sort_words(words, d),把统计结果存入目标文件d
时间: 2023-06-26 10:08:45 浏览: 48
以下是Python代码实现:
```python
import re
from collections import Counter
def count_words(src_file):
with open(src_file, 'r') as f:
text = f.read()
words = re.findall(r'\b\w+\b', text.lower()) # 将文本中的单词全部转为小写,再使用正则表达式匹配出所有的单词
word_counts = Counter(words) # 使用Counter进行统计
return word_counts
def sort_words(words, dest_file):
sorted_words = sorted(words.items(), key=lambda x: x[1], reverse=True) # 对统计结果进行降序排列
with open(dest_file, 'w') as f:
for word, count in sorted_words:
f.write(f"{word} {count}\n") # 将统计结果写入目标文件
# 示例调用
words = count_words('example.txt')
sort_words(words, 'result.txt')
```
其中,`count_words()` 函数使用正则表达式匹配出所有的单词,再使用 `collections` 模块中的 `Counter` 类进行统计,并返回统计结果。
`sort_words()` 函数接受一个字典类型的参数 `words`,将其按照值降序排列后,写入目标文件中。
示例调用中,先调用 `count_words()` 统计源文件中的单词出现次数,并将统计结果存储在 `words` 变量中,然后调用 `sort_words()` 将统计结果写入目标文件。