写一个脚本,统计文件file1中的每个单词出现的次数,以及全文单词的总数。,注意是脚本,
时间: 2024-02-24 18:00:19 浏览: 28
好的,以下是 Python 脚本实现:
```python
import re
file_path = 'file1.txt' # 将路径替换为你的文件路径
word_count = {}
total_count = 0
with open(file_path, 'r') as f:
for line in f:
words = re.findall(r'\w+', line) # 找到所有的单词
for word in words:
word = word.lower() # 将单词转换为小写
total_count += 1
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
print('单词\t\t出现次数')
print('=======================')
for word, count in word_count.items():
print(f'{word}\t\t{count}')
print(f'总共出现了 {total_count} 个单词。')
```
这段代码会读取指定文件中的所有行,统计每个单词出现的次数,以及全文单词的总数。输出结果会按照单词出现次数从高到低排序。你只需要将 `file_path` 变量替换为你的文件路径即可。