【发布时间】:2018-07-18 04:45:19
【问题描述】:
我正在使用 Python 3.6.3 获取 TV/Play/whatever 脚本并将其分类到字典中,该字典将字符及其对话行配对。
我已经能够得到我想要的结果,它为每个 Character: 嵌套了 {Line#:Line} 对,但我想知道是否有更有效的方法来达到这一点。特别是我最初拆分文本的方式,我首先获取对话中各个单词的列表,然后通过遍历字典的副本来加入这些列表。
import re
text = """
Steve: Is that his chart?
Phil: Yes.
Steve: Mm-hmm. I'll see him in a few moments.
Phil: All right. Thank you, Doctor.
P.A.: Dr. Braun, Dr. Miller, and Dr. Sullivan, emergency.
Steve: How is she, Jessie?
Jessie: Still fighting everybody and everything. She wants to live in the
dark and never see her face again. That's about what she was doing when I went
in. She had the blinds all drawn, towel over the mirror. """
## general hospital!
dialog = {}
count = 0
cast = []
for word in text.split():
if re.match(".*\:", word):
character = word[:-1]
count += 1
if character not in dialog:
cast.append(character)
dialog[character] = {}
dialog[character][count] = []
else:
dialog[character][count] = []
else:
dialog[character][count].append(word)
fullLines = {}
for k,v in dialog.items():
fullLines[k] = {}
for k1,v1 in v.items():
v1 = ' '.join(v1)
fullLines[k][k1] = v1
有没有一种方法可以使用正则表达式拆分文本以识别对话提示 - “字符:”并用它拆分文本?我试着放置
re.compile(r".*\:") 变成 split() 就像这样
match = re.compile(".*\:")
for word in text.split(match):
并得到错误TypeError: must be str or None, not _sre.SRE_Pattern。所以我基本上明白为什么这不起作用。我还在学习python,所以还在积累方法和pythonic的习惯。
【问题讨论】:
-
你想要的输出是什么?
-
这是我目前得到的:
-
` {'Steve': {1: '这是他的图表吗?', 3: "嗯-嗯。我一会儿见他。", 6: '她怎么样, Jessie?'}, 'Phil': {2: 'Yes.', 4: '好吧。谢谢你,博士。'},'P.A.':{5:'博士。布劳恩、米勒博士和沙利文博士,紧急情况。'},“杰西”:{7:“仍在与每个人和所有事情作斗争。她想生活在黑暗中,再也见不到她的脸。这就是她正在做的事情当我进去的时候。她把百叶窗都拉上了,毛巾盖在镜子上。”}}`
-
这是我的目标,但我想知道我是否以一种过于复杂的方式到达那里。
标签: python regex dictionary