【问题标题】:Extract words after a particular word在特定单词之后提取单词
【发布时间】:2021-08-01 08:34:50
【问题描述】:

我想在特定单词之后提取单词。例如,对于txt = 'I like to eat apple. Me too.',我想提取apple 之后的所有单词,即'.我也是。'

我试过了

re.findall(r"(apple[^.]*\.)",txt)  

但它返回到'apple.'

我也试过

`re.findall(r"([^.]*?apple[^.]*\.)",txt)`   

返回'I like to eat apple.'

【问题讨论】:

  • 这能回答你的问题吗? Finding words after keyword in python
  • 也许我遗漏了一些东西,但正则表达式不应该像apple(.*)$ 一样简单吗? apple 匹配关键字,然后 (.*)$ 捕获其他所有内容,直到 eol?

标签: python regex


【解决方案1】:

您不需要正则表达式。只需使用split

txt = 'I like to eat apple. Me too.'
print(txt.split("apple")[1])

输出

. Me too.

【讨论】:

    【解决方案2】:

    如果您想使用 RegEx 解决此问题,您可以使用lookbehind: (?

    txt = 'I like to eat apple. Me too.'
    re.findall(r"(?<=apple).*", txt);
    

    如果前面有 reg.exp,它会匹配所有内容 (.*)。 苹果

    【讨论】:

      【解决方案3】:
      def findAfter (text, after):
              start = text.find (after) #Sets start to the start of keyword
              end = start + len (after) #Sets end to the end of the keyword
              return text [end : ] #Returns everything from the of the keyword 
      

      在你的例子中:

      txt = 'I like to eat apple. Me too.'
      keyword = 'apple'
      findAfter (txt, keyword)
      

      经过测试并为我工作。如果有任何不清楚的地方,请发表评论。

      【讨论】:

        猜你喜欢
        • 2021-12-31
        • 2019-10-10
        • 2021-07-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多