给出一个actor列表,它们的字符名称用括号括起来,用分号(;)或comm(,)分隔:
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]
我如何以[(演员,角色),......的形式将其解析为两种类型的列表...]
--> [('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)]
但这不太有效,因为它也会将项目拆分为括号。
答案 0 :(得分:4)
您可以使用以下内容:
>>> re.findall(r'(\w[\w\s\.]+?)\s*\[([\w\s;\.,]+)\][,;\s$]*', s)
[('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')]
还可以使用.*?
来简化某些事情:
re.findall(r'(\w.*?)\s*\[(.*?)\][,;\s$]*', s)
答案 1 :(得分:1)
inputData = inputData.replace("];", "\n")
inputData = inputData.replace("],", "\n")
inputData = inputData[:-1]
for line in inputData.split("\n"):
actorList.append(line.partition("[")[0])
dataList.append(line.partition("[")[2])
togetherList = zip(actorList, dataList)
这有点像黑客,我相信你可以从这里清理它。我将介绍这种方法,以确保您了解我正在做的事情。
我用换行符替换了;
和,
,我稍后会用它来将每一对拆分成自己的行。假设您的内容没有填充错误的];
或],
,这应该可行。但是,您会注意到最后一行最后会有]
,因为它不需要逗号或分号。因此,我用第三行拼接它。
然后,只需在输入字符串中创建的每一行上使用分区函数,我们将左侧部分分配给actor列表,右侧部分分配给数据列表并忽略括号(位于位置1)。
之后,Python非常有用的zip函数应该通过将每个列表的i
元素组合到一个匹配的元组列表中来完成我们的工作。