Python 获取特定单词后面的所有单词
我有一个包含如下字符串的列表:Python 获取特定单词后面的所有单词,python,Python,我有一个包含如下字符串的列表: ['White Buns (Hot Dog)', ' 2 x Danish (Almond Danish) - A delight with coffee! \nThe best fruit fillings and of coarse butter filled flaky puff pastry.\n'] 我想得到括号中所有单词之前的所有单词,以及括号中的单词,以便得到以下内容: White Buns (Hot Dog) 2 x Danish (Almond
['White Buns (Hot Dog)', ' 2 x Danish (Almond Danish) - A delight with coffee! \nThe best fruit fillings and of coarse butter filled flaky puff pastry.\n']
我想得到括号中所有单词之前的所有单词,以及括号中的单词,以便得到以下内容:
White Buns (Hot Dog)
2 x Danish (Almond Danish)
有没有办法做到这一点?我尝试过正则表达式,但不知道如何指定(括号中的一个词)要指定parenthensis,可以使用“\)”(等于“)”)和“\(”(等于“(”) 结果:
t2 x Danish (Almond Danish)
t2 x Danish
(Almond Danish)
我将使用:
无论是否存在)
,该选项都有效
鉴于:
li=['No paren in this string...',
'Divide me (after) <- please',
'More that (1) paren (2) here']
>>> [''.join(s.partition(')')[:2]) for s in li]
['No paren in this string...', 'Divide me (after)', 'More that (1)']
不要忘记在
([^]*[)]
或re.sub之后的*
,只要重新组合字符串即可。以下是实现此目的的方法
list1=['White Buns(Hot Dog)','2 x Danish(杏仁丹麦)-与咖啡搭配的美味!\n最好的水果馅料和粗黄油馅的酥饼。\n']
对于列表1中的单词:
对于i,枚举中的字母(单词):
如果字母==')':
b、 追加(字[0:i+1])
印刷品(b)
输出
['White Buns (Hot Dog)', ' 2 x Danish (Almond Danish)']
为什么第二线没有2X?我错了。应该包括说l1
是列表。您可以执行以下操作:对于l1中的元素:打印(元素[:elem.find('))+1])
。对于这个问题,您不需要正则表达式。@ggaurav:elem[:elem.find('))+1]
将删除任何不包含)
的字符串。这可能是可取的,也可能不是可取的。@dawg,是的。我的回答假设括号总是存在的,事实上,问题听起来是这样的
li=['No paren in this string...',
'Divide me (after) <- please',
'More that (1) paren (2) here']
>>> [''.join(s.partition(')')[:2]) for s in li]
['No paren in this string...', 'Divide me (after)', 'More that (1)']
>>> [re.sub(r'([^)]*[)]).*', r'\1', s) for s in li]
['No paren in this string...', 'Divide me (after)', 'More that (1)']
['White Buns (Hot Dog)', ' 2 x Danish (Almond Danish)']