python - 如何计算对话中每个角色所说的单词数并将计数存储在字典中?
问题描述
我正在尝试计算角色"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] 的列表
我想我需要以下帮助:
- 如果可能的话,一个更好的方法
- 当该行是对话的最后一行时,一种计算角色所说单词数的方法
- 一种通过自动计算角色所说的单词来更新字典的方法
最后一点至关重要,因为我试图复制这个过程以获得一集的引用。
先感谢您!
解决方案
循环遍历单词,在进行时增加适当的计数。
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
顺便说一句,不要使用list
anddict
作为变量名,这会用这些名称覆盖内置函数。
推荐阅读
- c++ - 向其中添加 lambda 时 Catkin 构建失败
- javascript - 解决方案,“onpopstate”事件在 chrome 中不起作用,但在 IE 和 FireFox 中运行良好
- java - 按列表中某些对象中缺少的对象字段对列表进行排序
- javascript - 在 asp.net 中使用 GridView 进行编辑功能 - 下拉列表
- javascript - 我想在会话被破坏或用户注销时隐藏图像按钮
- visual-studio-code - 我们如何使单个键绑定到匹配的括号,以及 emmet 匹配的标签?
- excel - 在 Excel 文档中自动打开一个 URL,每次生成一个
- google-cloud-platform - GKE 错误“代码=400,消息=IP 别名不能用于旧网络。”
- python - Python Selenium错误元素在点不可点击
- ubuntu-16.04 - 如何忽略 Systemd 中的“ExecStart”失败