python统计红楼梦人物出场次数_《红楼梦》人数统计,人物,出场,次数
时间: 2023-08-01 16:09:13 浏览: 140
可以使用Python中的字典(dictionary)来统计《红楼梦》中人物的出场次数。具体步骤如下:
1. 打开《红楼梦》的文本文件,读取所有内容。
```python
with open('hongloumeng.txt', 'r', encoding='utf-8') as f:
content = f.read()
```
2. 使用正则表达式(re)匹配出文本中所有的人名。
```python
import re
pattern = re.compile('[\u4e00-\u9fa5]{2,4}(?:·[\u4e00-\u9fa5]{2,4})*')
names = re.findall(pattern, content)
```
3. 使用字典统计每个人名出现的次数。
```python
name_count = {}
for name in names:
if name in name_count:
name_count[name] += 1
else:
name_count[name] = 1
```
4. 对字典按照值(出现次数)进行排序。
```python
sorted_name_count = sorted(name_count.items(), key=lambda x:x[1], reverse=True)
```
完整代码如下:
```python
import re
with open('hongloumeng.txt', 'r', encoding='utf-8') as f:
content = f.read()
pattern = re.compile('[\u4e00-\u9fa5]{2,4}(?:·[\u4e00-\u9fa5]{2,4})*')
names = re.findall(pattern, content)
name_count = {}
for name in names:
if name in name_count:
name_count[name] += 1
else:
name_count[name] = 1
sorted_name_count = sorted(name_count.items(), key=lambda x:x[1], reverse=True)
for name, count in sorted_name_count:
print(name, count)
```
输出结果为每个人名以及出现的次数,可以根据需要进行进一步的处理和分析。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)