【问题标题】:Extract words/sentence that occurs before a keyword from a string - Python从字符串中提取出现在关键字之前的单词/句子 - Python
【发布时间】:2018-02-23 18:16:39
【问题描述】:

我有一个这样的字符串,

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").'

现在,我想使用关键字 championunderdog 提取当前的 championunderdog

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

以下是我所做的,

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

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

【问题讨论】:

    标签: python regex keyword matching


    【解决方案1】:

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

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

    • 之后,\s+and\s+(?P&lt;underdog&gt;.*?)\s+\("underdog"\) 将块匹配到 ("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】:

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

      下面是我的做法:

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

      对于失败者,您必须将 6 更改为 7,并将 '("champion")' 更改为 '("underdog").'

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

      如果失败者的尾随句点有问题,您也可以使用str.strip() 删除标点符号。

      【讨论】:

      • 它给你什么输出?
      • print(champion) 给我'ch, da'
      • 哎呀。请参阅我的编辑。 my_str 的一个实例已替换为 words
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-14
      • 2013-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-28
      相关资源
      最近更新 更多