python西游记词频统计
时间: 2023-11-21 15:56:30 浏览: 129
以下是Python实现《西游记》词频统计的代码和步骤:
1. 读取《西游记》文本文件
```python
with open('xyj.txt', 'r', encoding='utf-8') as f:
text = f.read()
```
2. 使用正则表达式去除文本中的非汉字字符
```python
import re
text = re.sub('[^\u4e00-\u9fa5]', '', text)
```
3. 统计每个汉字出现的次数
```python
from collections import Counter
counter = Counter(text)
```
4. 统计不同汉字的个数
```python
num_unique_chars = len(counter)
```
5. 找出出现次数最多的前10个汉字
```python
most_common = counter.most_common(10)
```
6. 将结果保存到json文件中
```python
import json
result = {
'num_unique_chars': num_unique_chars,
'most_common': most_common,
'counter': dict(counter)
}
with open('result.json', 'w', encoding='utf-8') as f:
json.dump(result, f, ensure_ascii=False, indent=4)
```
阅读全文
相关推荐


















