【发布时间】:2021-07-02 01:43:00
【问题描述】:
我正在尝试计算字符 "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] 的列表
我想我需要以下帮助:
- 如果可能的话,一个更好的方法
- 当该行是对话的最后一行时,一种计算角色说出的单词数的方法
- 一种通过自动计算角色说出的单词数来更新字典的方法
最后一点至关重要,因为我试图复制这个过程以获得一集的引语。
提前谢谢你!
【问题讨论】:
-
不使用内置函数作为变量
-
@Sujay 的意思是
string是一个 std 库模块,因此您可以通过将其用作变量名使其不可用(是的,您可以import string as still_available_string)。 -
@JLPeyret,还有
list和dict -
对,请注意,因为我只使用了 OPs 字符串定义。
-
@beginnerprogrammerforever 好...接受答案或为您认为有帮助的人点赞是这里感谢人们的常用方式。
标签: python string dictionary parsing