python读取文件数据count之后再输出前五
时间: 2023-08-12 10:41:59 浏览: 40
当然可以,请参考下面的代码实现:
```python
# 打开文件
with open('file.txt', 'r') as f:
# 读取文件内容
data = f.read()
# 将文件内容转换为单词列表,并统计每个单词的出现次数
word_count = {}
for word in data.split():
if word not in word_count:
word_count[word] = 1
else:
word_count[word] += 1
# 对单词出现次数进行排序
sorted_word_count = sorted(word_count.items(), key=lambda x: x[1], reverse=True)
# 输出前五个单词及其出现次数
for i in range(5):
print(sorted_word_count[i])
```
其中,'file.txt' 是要读取的文件名,你需要将其替换为你自己的文件名。
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)