You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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}

分步解释

  1. 导入工具类:从collections模块导入Counter,它是Python专门用于计数可迭代对象的工具类,能自动统计每个元素的出现次数。
  2. 提取角色名:用生成器表达式遍历dialogue元组的每个子列表,通过解构char, _取出第一个元素(角色名),直接忽略台词内容,避免不必要的内存占用。
  3. 统计与转换:将生成器传入Counter得到统计结果,再用dict()转换为普通字典,即可得到{"角色名": 次数}的目标格式。

内容的提问来源于stack exchange,提问作者Judith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 22:39:20