繁体   English   中英

在特定单词之后提取单词

[英]Extract words after a particular word

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

我试过了

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

但它返回到'apple.'

我也试过

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

它返回到'I like to eat apple.'

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

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

output

. Me too.

如果您想使用 RegEx 解决此问题,您可以使用lookbehind: (?<=...) 和 'apple' 替换点,然后匹配它之后的所有内容。

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

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

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)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM