首页 > 解决方案 > 如何计算对话中每个角色所说的单词数并将计数存储在字典中?

问题描述

我正在尝试计算角色"Michael""Jim"以下对话中所说的单词数,并将它们存储在一个看起来像{"Michael:":15, "Jim:":10}.

string = "Michael: All right Jim. Your quarterlies look very good. How are things at the library? Jim: Oh, I told you. I couldn’t close it. So… Michael: So you’ve come to the master for guidance? Is this what you’re saying, grasshopper? Jim: Actually, you called me in here, but yeah. Michael: All right. Well, let me show you how it’s done."

我想创建一个包含字符名称作为键的空字典,将字符串拆分" ",然后通过使用键作为参考来计算字符名称之间的结果列表元素的数量,然后将单词的计数存储为值。这是我到目前为止使用的代码:

dict = {"Michael:" : 0,
        "Jim:" : 0}

list = string.split(" ")

indices = [i for i, x in enumerate(list) if x in dict.keys()]
nums = []
for i in range(1,len(indices)):
    nums.append(indices[i] - indices[i-1])
print(nums)

结果是一个打印为 [15, 10, 15, 9] 的列表

我想我需要以下帮助:

  1. 如果可能的话,一个更好的方法
  2. 当该行是对话的最后一行时,一种计算角色所说单词数的方法
  3. 一种通过自动计算角色所说的单词来更新字典的方法

最后一点至关重要,因为我试图复制这个过程以获得一集的引用。

先感谢您!

标签: pythonstringdictionaryparsing

解决方案


循环遍历单词,在进行时增加适当的计数。

dialogue_dict = {"Michael:" : 0, "Jim:" : 0}

words = string.split(" ")
current_character = None
for word in words:
    if word in dialogue_dict:
        current_character = word
    elif current_character:
        dialogue_dict[current_character] += 1

顺便说一句,不要使用listanddict作为变量名,这会用这些名称覆盖内置函数。


推荐阅读