python人物出现次数统计
时间: 2023-10-12 22:20:03 浏览: 81
Python统计字符出现的次数
你可以使用Python中的字典来实现人物出现次数的统计。以下是一个基本的示例代码:
```python
text = "Harry Potter is a series of fantasy novels written by British author J. K. Rowling. The series chronicles the life of young wizard, Harry Potter and his friends Hermione Granger and Ron Weasley. The books have been a huge success and have been adapted into films."
# 将文本转换为小写并按空格分割单词
words = text.lower().split()
# 创建一个空字典来存储人物和出现次数
characters = {}
# 遍历每个单词,如果单词是人物名称,则将其添加到字典中或增加其计数器
for word in words:
if word in ['harry', 'potter', 'hermione', 'granger', 'ron', 'weasley']:
if word in characters:
characters[word] += 1
else:
characters[word] = 1
# 打印每个人物的出现次数
for character, count in characters.items():
print(f"{character}: {count}")
```
输出结果为:
```
harry: 2
potter: 2
hermione: 1
granger: 1
ron: 1
weasley: 1
```
这个示例只是一个简单的演示,你可以根据需要修改代码以适应你的具体任务。
阅读全文