【问题标题】:Python extracting sentence containing word excluding the numeric stringsPython提取包含不包括数字字符串的单词的句子
【发布时间】: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


【解决方案1】:

使用lookahead regex 断言匹配以. 结尾,后面不跟数字

这适用于您的示例输入,但可能需要稍微调整以更通用以处理更多案例。

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.*?\.)(?!\d)" % define_words,txt))
# The apt subtitle for the binoculars will be 9015.18.1190, CTS, which provides for binoculars.

【讨论】:

  • 嘿,你是对的.. 我刚刚了解到问题不在于数字.. 句子中有大括号和双引号.. 我可以使用 txt=str(txt).strip('()') 删除大括号,但我无法删除双引号。然而,这些双引号并非出现在所有句子中。我该如何处理它们?
  • 双引号在哪里,你能显示示例和预期输出吗?您可以使用txt = txt.strip('()"') 去掉圆括号和双引号
猜你喜欢
  • 2016-04-21
  • 2013-04-08
  • 2023-04-03
  • 2023-03-24
  • 2013-09-02
  • 2018-01-08
  • 1970-01-01
  • 2014-05-20
  • 1970-01-01
相关资源
最近更新 更多