【发布时间】:2017-04-27 02:46:49
【问题描述】:
我有一个类似的问题,在这个链接Python extract sentence containing word 中讨论过,但我不想用数字字符串结束句子。
例如:
The apt subtitle for the binoculars will be 9015.18.1190, CTS, which provides for binoculars. The rate of duty on this will be free.
当我尝试这个时:
import re
txt="The apt subtitle for the binoculars will be 9015.18.1190, CTS, which provides for binoculars. The rate of duty on this will be free."
define_words = 'apt subtitle'
print (re.findall(r"([^.]*?%s[^.]*\.)" % define_words,txt))
实际输出:
The apt subtitle for the binoculars will be 9015.
但是预期的输出是:
The apt subtitle for the binoculars will be 9015.18.1190, CTS, which provides for binoculars.
有人可以帮我实现预期的输出吗?
【问题讨论】:
-
如果只有一句话(
txt)需要处理,直接使用txt.split('The rate of duty on this will be free.')[0]即可。但是,如果要处理的句子很多,这不会为您提供系统的解决方案 -
您可以对句子进行拆分,然后查找句子中是否存在所需的单词,然后打印该句子。
标签: python regex python-2.7 python-3.x