python - Python Regex - 提取包含相同关键字的多个句子
问题描述
import re
regex = r"[^.?!-]*(?<=[.?\s!-])\b(pfs)\b(?=[\s.?!-])[^.?!-]*[.?!-]"
test_str = "pfs alert conf . it is unlikely that we will sign it - pfs of $ 950 filed to driver - we are gathering information"
subst = ""
result = re.sub(regex, subst, test_str, 0, re.IGNORECASE | re.MULTILINE)
if result:
print (result)
如我们所见,test_str 有两个带有关键字“pfs”的句子。但是,上面的python代码只能提取第二句'pfs of 950 filed to driver',如何修改它以提取'pfs alert conf'呢?
解决方案
考虑nltk
改用,imo它真的更适合这里:
from nltk import sent_tokenize
test_str = "pfs alert conf . it is unlikely that we will sign it - pfs of $ 950 filed to driver - we are gathering information. some junky words thereafter"
sentences = [sent for sent in sent_tokenize(test_str) if "pfs" in sent]
print(sentences)
这会产生(注意最后一句没有pfs
):
['pfs alert conf .',
'it is unlikely that we will sign it - pfs of $ 950 filed to driver - we are gathering information.']
推荐阅读
- bash - 如何在 grep 中将多行视为一个结果,或者至少在不改变的情况下过滤
- elasticsearch - 弹性搜索词序
- r - 将列表列添加到数据框
- javascript - React 将其链接为地图内的状态
- raspberry-pi3 - 是否可以通过 OpenPLC ModBus 控制 %QX0.0 LED 灯?
- sql - 如何修复“用于插入的 Sql 触发器不适用于声明变量”
- azure - 无法使用用户分配的托管标识检索 keyvault 机密
- excel - 如何使用 PowerShell 在列中搜索包含文本并在新列中返回数据?
- android - 如何通过 intent-filter 和 action.SEND_MULTIPLE 接收多个 vcard
- javascript - 显示当前标签 javascript