从字符串Python中提取出现在关键字之前的单词/句子

2024-10-06 07:09:08 发布

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

我有一根这样的绳子

my_str ='·in this match, dated may 1, 2013 (the "the match") is between brooklyn centenniel, resident of detroit, michigan ("champion") and kamil kubaru, the challenger from alexandria, virginia ("underdog").'

现在,我想使用关键字champion和{}提取当前的{}和{}。在

真正具有挑战性的是两个竞争者的名字都出现在括号内的关键字之前。我想使用正则表达式并提取信息。在

以下是我所做的

^{pr2}$

但是,我需要结果,champion as

brooklyn centenniel, resident of detroit, michigan

并且underdog为:

kamil kubaru, the challenger from alexandria, virginia

如何使用正则表达式完成此操作?(我一直在搜索,如果我可以从关键字中返回两个或多个词来得到我想要的结果,但还没有运气)任何帮助或建议将不胜感激。在


Tags: ofthefrommatch关键字residentchampionalexandria
2条回答

您可以使用命名捕获组来捕获所需的结果:

between\s+(?P<champion>.*?)\s+\("champion"\)\s+and\s+(?P<underdog>.*?)\s+\("underdog"\)
  • between\s+(?P<champion>.*?)\s+\("champion"\)匹配从between到{}的块,并将所需的部分作为命名的捕获组champion

  • 在此之后,\s+and\s+(?P<underdog>.*?)\s+\("underdog"\)将块匹配到("underdog"),并再次从这里获得所需的部分,命名为捕获组underdog

示例:

^{pr2}$

会有比这更好的答案,我根本不懂正则表达式,但我很无聊,所以这是我的2美分。在

我会这样做:

words = my_str.split()
index = words.index('("champion")')
champion = words[index - 6:index]
champion = " ".join(champion)

对于弱者,你必须将6改为7,并将'("champion")'改为'("underdog").'

不确定这是否能解决您的问题,但对于这个特定的字符串,当我测试它时,它起作用了。在

如果underdog后面的句点有问题,也可以使用str.strip()删除标点符号。在

相关问题 更多 >