Python提取包含单词的句子

新手上路,请多包涵

我正在尝试从文本中提取所有包含指定单词的句子。

 txt="I like to eat apple. Me too. Let's go buy some apples."
txt = "." + txt
re.findall(r"\."+".+"+"apple"+".+"+"\.", txt)

但它正在返回我:

 [".I like to eat apple. Me too. Let's go buy some apples."]

代替 :

 [".I like to eat apple., "Let's go buy some apples."]

有什么帮助吗?

原文由 user2187202 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 431
2 个回答
In [3]: re.findall(r"([^.]*?apple[^.]*\.)",txt)
Out[4]: ['I like to eat apple.', " Let's go buy some apples."]

原文由 Kent 发布,翻译遵循 CC BY-SA 3.0 许可协议

不需要正则表达式:

 >>> txt = "I like to eat apple. Me too. Let's go buy some apples."
>>> [sentence + '.' for sentence in txt.split('.') if 'apple' in sentence]
['I like to eat apple.', " Let's go buy some apples."]

原文由 jamylak 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题