Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从字符串中提取关键字之前出现的单词/句子-Python_Python_Regex_Keyword_Matching - Fatal编程技术网

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

从字符串中提取关键字之前出现的单词/句子-Python,python,regex,keyword,matching,Python,Regex,Keyword,Matching,我有一根这样的绳子 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和underdog提取

我有一根这样的绳子

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
underdog
提取当前的
champion
underdog

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

下面是我所做的

champion = re.findall(r'("champion"[^.]*.)', my_str)
print(champion)

>> ['"champion") and kamil kubaru, the challenger from alexandria, virginia ("underdog").']


underdog = re.findall(r'("underdog"[^.]*.)', my_str)
print(underdog)

>>['"underdog").']
但是,我需要结果,
champion as

brooklyn centenniel, resident of detroit, michigan
下位机
为:

kamil kubaru,来自弗吉尼亚州亚历山大市的挑战者


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

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

between\s+(?P<champion>.*?)\s+\("champion"\)\s+and\s+(?P<underdog>.*?)\s+\("underdog"\)

有比这个更好的答案,我一点也不懂正则表达式,但我很无聊,所以这是我的2美分

下面是我将如何着手的:

words = my_str.split()
index = words.index('("champion")')
champion = words[index - 6:index]
champion = " ".join(champion)
对于弱者,您必须将6改为7,并将
'(“冠军”)
改为
'(“弱者”)。

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


如果在underdog上的尾随句点有问题,您还可以使用删除标点符号

它给了你什么输出?
print(champion)
给了我
'ch,da'
oops。请参阅我的编辑。
my_str
的一个实例已替换为
words
words = my_str.split()
index = words.index('("champion")')
champion = words[index - 6:index]
champion = " ".join(champion)