给定一个演员列表,其角色名称在括号中,用分号(;)或逗号(,)分隔:
Shelley Winters [Ruby]; Millicent Martin [Siddie]; Julia Foster [Gilda];
Jane Asher [Annie]; Shirley Ann Field [Carla]; Vivien Merchant [Lily];
Eleanor Bron [Woman Doctor], Denholm Elliott [Mr. Smith; abortionist];
Alfie Bass [Harry]
我如何将其解析为两个typle的列表,其形式为[(actor,character),…]
--> [('Shelley Winters', 'Ruby'), ('Millicent Martin', 'Siddie'),
('Denholm Elliott', 'Mr. Smith; abortionist')]
我最初有:
actors = [item.strip().rstrip(']') for item in re.split('\[|,|;',data['actors'])]
data['actors'] = [(actors[i], actors[i + 1]) for i in range(0, len(actors), 2)]
但这并不是很有效,因为它还将括号内的项拆分。你知道吗
这是一个有点黑客,我相信你可以清理它从这里。我将通过这个方法来确保你明白我在做什么。你知道吗
我将用换行符替换
;
和,
,稍后我将使用换行符将每个对拆分为自己的行。假设您的内容中没有填充错误的];
或],
,这应该是可行的。但是,您会注意到最后一行的末尾将有一个]
,因为它不需要逗号或分号。因此,我把它和第三条线连接起来。你知道吗然后,只需在输入字符串中创建的每一行上使用分区函数,就可以将左部分指定给actor列表,将右部分指定给data列表,并忽略括号(位于位置1)。你知道吗
之后,Python非常有用的zip函数应该通过将每个列表的第
i
元素关联到一个匹配元组列表中来完成这项工作。你知道吗你可以这样做:
也可以用
.*?
简化一些事情:相关问题 更多 >
编程相关推荐