python三国演义人物出场统计代码含义
时间: 2023-07-09 08:33:58 浏览: 55
这段代码的含义是统计《三国演义》中各个人物出场次数,并按照出场次数从高到低排列。
具体实现方法是,先读取《三国演义》文本文件,然后将每个人物出现的次数存储在一个字典中,最后按照字典中的值进行排序并输出。
以下是代码示例:
```python
import re
# 读取《三国演义》文本文件
with open('sanguo.txt', 'r', encoding='utf-8') as f:
sanguo = f.read()
# 使用正则表达式匹配人物名字
pattern = re.compile('[\u4e00-\u9fa5]{2,4}(?:·[\u4e00-\u9fa5]{2,4})*')
names = pattern.findall(sanguo)
# 统计人物出现次数
dict = {}
for name in names:
if name in dict:
dict[name] += 1
else:
dict[name] = 1
# 按照出现次数从高到低排序并输出
sorted_dict = sorted(dict.items(), key=lambda x:x[1], reverse=True)
for item in sorted_dict:
print(item[0], item[1])
```
相关问题
python三国演义人物出场前十统计代码含义
以下是Python代码实现:
```python
# 导入必要的库和数据
import jieba
from collections import Counter
with open("sanguo.txt", "r", encoding="utf-8") as f:
content = f.read()
# 分词并去除停用词
stopwords = [line.strip() for line in open('stopwords.txt', 'r', encoding='utf-8').readlines()]
words = [word for word in jieba.cut(content) if word not in stopwords and len(word) > 1]
# 统计前十人物出场次数
top10 = Counter(words).most_common(10)
for i, item in enumerate(top10):
print("第{}名: {},出现{}次".format(i+1, item[0], item[1]))
```
代码含义:
1. 导入必要的库和数据:导入`jieba`分词库和`collections`中的`Counter`计数器,同时读入三国演义的文本文件`sanguo.txt`。
2. 分词并去除停用词:使用`jieba`分词将文本内容拆分为单个词语,并去除停用词。
3. 统计前十人物出场次数:使用`Counter`计数器统计每个词语出现的次数,并取出前十个出现次数最多的词语,即前十个人物,最后输出其出现次数。其中,`most_common()`方法可以根据元素出现的次数,从大到小返回一个包含元素及其计数的列表。
python三国演义人物出场统计前20
好的,以下是Python三国演义人物出场统计前20的代码:
```python
import jieba
# 读取文本文件
with open('sanguo.txt', 'r', encoding='utf-8') as f:
sanguo = f.read()
# 使用jieba分词
words = jieba.lcut(sanguo)
# 统计人物出现次数
counts = {}
for i in range(len(words) - 1):
if words[i] == '诸葛亮' or words[i] == '孔明曰':
if words[i+1] != '曰':
name = words[i+1]
if name in counts:
counts[name] += 1
else:
counts[name] = 1
# 排序并输出前20名
top20 = sorted(counts.items(), key=lambda x: x[1], reverse=True)[:20]
for i in range(len(top20)):
print(f'{i+1}. {top20[i][0]}: {top20[i][1]}')
```
注意,以上代码需要在安装了jieba库的Python环境中运行,而且需要将三国演义的文本文件命名为`sanguo.txt`并与代码放在同一目录下。