如何用Counter统计元组中角色台词次数并转换为字典?
用Counter统计戏剧角色发言次数的解决方案
核心思路
遍历元组中每个包含角色与台词的子列表,提取所有角色名,再用collections.Counter自动统计每个角色的发言次数,最后转换为目标字典格式。
完整代码实现
from collections import Counter # 给定的对话元组 dialogue = (['Benvolio','Part, fools!\nPut up your swords; you know not what you do.'], ['Tybalt', 'What, art thou drawn among these heartless hinds?\nTurn thee, Benvolio, look upon thy death.'], ['Benvolio', 'I do but keep the peace: put up thy sword,\nOr manage it to part these men with me.'], ['Tybalt', 'What, drawn, and talk of peace! I hate the word,\nAs I hate hell, all Montagues, and thee:\nHave at thee, coward!\n[They fight]\n[Enter, several of both houses, who join the fray;]\nthen enter Citizens, with clubs]']) # 提取所有角色名(生成器表达式节省内存) character_iter = (char for char, _ in dialogue) # 统计次数并转为目标字典格式 count_result = dict(Counter(character_iter)) print(count_result) # 输出: {'Benvolio': 2, 'Tybalt': 2}
分步解释
- 导入工具类:从
collections模块导入Counter,它是Python专门用于计数可迭代对象的工具类,能自动统计每个元素的出现次数。 - 提取角色名:用生成器表达式遍历
dialogue元组的每个子列表,通过解构char, _取出第一个元素(角色名),直接忽略台词内容,避免不必要的内存占用。 - 统计与转换:将生成器传入
Counter得到统计结果,再用dict()转换为普通字典,即可得到{"角色名": 次数}的目标格式。
内容的提问来源于stack exchange,提问作者Judith
相关产品推荐
相关产品推荐

