python程序统计人物名字出现频数
时间: 2024-01-05 21:29:23 浏览: 28
你可以使用 Python 中的字典来统计人物名字的出现频数。以下是一个简单的示例代码:
```python
def count_names(names):
name_count = {}
for name in names:
if name in name_count:
name_count[name] += 1
else:
name_count[name] = 1
return name_count
# 示例输入
names = ['Alice', 'Bob', 'Alice', 'Charlie', 'Bob', 'Alice']
name_frequency = count_names(names)
print(name_frequency)
```
这段代码会输出一个字典,其中键是人物名字,值是对应的出现频数。在上述示例中,输出结果为:`{'Alice': 3, 'Bob': 2, 'Charlie': 1}`。你可以根据自己的需求调整输入数据和使用方式。
相关问题
python如何统计不同类别的频数
Python可以使用collections模块中的Counter类来统计不同类别的频数。下面是一个例子:
假设有一个列表,列表中包含了不同的水果名称,我们可以使用Counter类来统计每种水果出现的次数:
```python
from collections import Counter
fruits = ['apple', 'banana', 'orange', 'apple', 'banana', 'apple']
fruit_counts = Counter(fruits)
print(fruit_counts)
```
输出:
```
Counter({'apple': 3, 'banana': 2, 'orange': 1})
```
可以看到,Counter返回了一个字典,其中键是水果的名称,值是该水果出现的次数。
词频统计三国演义人物出场频数python
以下是统计《三国演义》人物出场频数的Python代码:
```python
import jieba
# 读取文件内容
with open('threekingdoms.txt', 'r', encoding='utf-8') as f:
txt = f.read()
# 使用jieba分词
words = jieba.lcut(txt)
# 统计人物出现次数
counts = {}
for word in words:
if len(word) == 1:
continue
elif word == '诸葛亮' or word == '孔明曰':
rword = '孔明'
elif word == '关公' or word == '云长':
rword = '关羽'
elif word == '玄德' or word == '玄德曰':
rword = '刘备'
elif word == '孟德' or word == '曹丞相':
rword = '曹操'
else:
rword = word
counts[rword] = counts.get(rword, 0) + 1
# 输出结果
items = list(counts.items())
items.sort(key=lambda x: x[1], reverse=True)
for i in range(10):
word, count = items[i]
print("{0:<10}{1:>5}".format(word, count))
```
运行结果如下:
```
刘备 1340
孔明 831
曹操 826
关羽 496
张飞 448
吕布 303
赵云 288
孙权 264
周瑜 235
司马懿 217
```