8.《射雕英雄传》是金庸的重要武侠作品之一。这里给出一个《射雕英雄传》的网络版本,文件名为“射雕英雄传-网络版.txt”。请编写程序,统计该文件出现的所有中文词语及出现次数,要求:以CSV格式输出到文件“射雕英雄传-词频统计.txt”中。CSV格式如下:词语1:233,词语2:564,词语3:344,……(2)在屏幕上打印输出词频最高的8个词语。屏幕输出格式如下:词语1,词语2,词语3,词语4,词语5,词语6,词语7,词语8
时间: 2024-01-13 20:02:41 浏览: 288
以下是一个Python代码示例,可以实现对《射雕英雄传》文件中中文词语的统计,并将结果以CSV格式输出到文件中,并在屏幕上打印词频最高的8个词语:
```python
import re
import csv
from collections import Counter
# 读取文件内容
with open('射雕英雄传-网络版.txt', 'r', encoding='utf-8') as f:
content = f.read()
# 使用正则表达式提取中文词语
pattern = re.compile('[\u4e00-\u9fa5]+')
words = pattern.findall(content)
# 统计词频并按降序排序
counter = Counter(words)
sorted_words = sorted(counter.items(), key=lambda x: x[1], reverse=True)
# 将结果输出到文件中
with open('射雕英雄传-词频统计.txt', 'w', encoding='utf-8') as f:
writer = csv.writer(f)
for word, count in sorted_words:
writer.writerow([f'{word}:{count}'])
# 在屏幕上打印词频最高的8个词语
top8 = sorted_words[:8]
print('词语1\t词语2\t词语3\t词语4\t词语5\t词语6\t词语7\t词语8')
for word, count in top8:
print(f'{word}\t', end='')
print()
```
首先,我们使用`open()`函数打开《射雕英雄传》文件,并以utf-8编码模式读取文件内容。然后,我们使用正则表达式提取中文词语,并将其保存在列表`words`中。
接下来,我们使用`collections`模块的`Counter`类统计每个中文词语出现的次数,并将结果按降序排列保存在列表`sorted_words`中。
然后,我们使用`csv`模块将`sorted_words`列表中的每个词语及其出现次数输出到文件“射雕英雄传-词频统计.txt”中,格式为CSV格式。
最后,我们从`sorted_words`列表中取出前8个词语,保存在列表`top8`中,并在屏幕上打印出这8个词语,以及它们的词频。
需要注意的是,这个代码示例假设《射雕英雄传》文件以utf-8编码保存。如果实际情况不同,需要根据实际情况修改代码。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)