正则表达式帮助将列表拆分为两个元组

2024-09-29 07:27:34 发布

您现在位置:Python中文网/ 问答频道 /正文

给定一个演员列表,其角色名称在括号中,用分号(;)或逗号(,)分隔:

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)]

但这并不是很有效,因为它还将括号内的项拆分。你知道吗


Tags: 列表actorsitem括号martinsmithrubymr
2条回答
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列表,将右部分指定给data列表,并忽略括号(位于位置1)。你知道吗

之后,Python非常有用的zip函数应该通过将每个列表的第i元素关联到一个匹配元组列表中来完成这项工作。你知道吗

你可以这样做:

>>> 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)

相关问题 更多 >