红楼梦人物出现次数用python统计
时间: 2024-01-26 21:11:19 浏览: 156
好的,我可以帮你解决这个问题。首先,我们需要获取《红楼梦》的文本数据。这里我选择使用Python中的requests库和BeautifulSoup库来爬取小说内容。请确保你已经安装了这两个库。
以下是代码实现:
```python
import requests
from bs4 import BeautifulSoup
# 获取小说内容
url = 'https://www.shicimingju.com/book/hongloumeng.html'
response = requests.get(url)
response.encoding = 'utf-8'
soup = BeautifulSoup(response.text, 'html.parser')
novel_content = soup.find('div', class_='book-mulu').next_sibling.next_sibling
# 统计人物出现次数
characters = {}
for p in novel_content.find_all('p'):
text = p.text.strip()
if text:
for char in text:
if char in characters:
characters[char] += 1
else:
characters[char] = 1
# 输出结果
for char, count in sorted(characters.items(), key=lambda x: x[1], reverse=True):
print(char, count)
```
运行以上代码,即可输出每个人物在小说中出现的次数。
阅读全文