[英]Extract words/sentence that occurs before a keyword from a string - 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
和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
和underdog
為:
kamil kubaru, the challenger from alexandria, virginia
我如何使用正則表達式來做到這一點? (我一直在搜索,如果我可以從關鍵字中返回幾個或幾個詞以獲得我想要的結果,但還沒有運氣)任何幫助或建議將不勝感激。
您可以使用命名捕獲組來捕獲所需的結果:
between\s+(?P<champion>.*?)\s+\("champion"\)\s+and\s+(?P<underdog>.*?)\s+\("underdog"\)
between\\s+(?P<champion>.*?)\\s+\\("champion"\\)
匹配從between
到("champion")
的塊,並將所需的部分放在中間作為命名的捕獲組champion
之后, \\s+and\\s+(?P<underdog>.*?)\\s+\\("underdog"\\)
匹配塊 upto ("underdog")
並再次從這里獲取所需的部分作為命名的捕獲組underdog
例子:
In [26]: 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").'
In [27]: out = re.search(r'between\s+(?P<champion>.*?)\s+\("champion"\)\s+and\s+(?P<underdog>.*?)\s+\("underdog"\)', my_str)
In [28]: out.groupdict()
Out[28]:
{'champion': 'brooklyn centenniel, resident of detroit, michigan',
'underdog': 'kamil kubaru, the challenger from alexandria, virginia'}
會有比這更好的答案,我根本不懂正則表達式,但我很無聊,所以這是我的 2 美分。
這是我將如何去做:
words = my_str.split()
index = words.index('("champion")')
champion = words[index - 6:index]
champion = " ".join(champion)
對於弱者,您必須將 6 更改為 7,並將'("champion")'
更改為'("underdog").'
不確定這是否能解決您的問題,但對於這個特定的字符串,當我測試它時,這有效。
如果失敗者的尾隨句點有問題,您還可以使用str.strip()刪除標點符號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.