python-3.x - 使用 spacy sentenizer 拆分句子
问题描述
我正在使用 spaCy 的语句器来拆分句子。
from spacy.lang.en import English
nlp = English()
sbd = nlp.create_pipe('sentencizer')
nlp.add_pipe(sbd)
text="Please read the analysis. (You'll be amazed.)"
doc = nlp(text)
sents_list = []
for sent in doc.sents:
sents_list.append(sent.text)
print(sents_list)
print([token.text for token in doc])
输出
['Please read the analysis. (',
"You'll be amazed.)"]
['Please', 'read', 'the', 'analysis', '.', '(', 'You', "'ll", 'be',
'amazed', '.', ')']
标记化已正确完成,但我不确定它不会将第二句与 ( 并将其作为第一句的结尾。
解决方案
我用 en_core_web_lg 和 en_core_web_sm 模型测试了下面的代码,sm 模型的性能类似于使用 sentencizer。(lg模型会影响性能)。
自定义边界以下仅适用于 sm 模型,并且与 lg 模型进行不同的拆分。
nlp=spacy.load('en_core_web_sm')
def set_custom_boundaries(doc):
for token in doc[:-1]:
if token.text == ".(" or token.text == ").":
doc[token.i+1].is_sent_start = True
elif token.text == "Rs." or token.text == ")":
doc[token.i+1].is_sent_start = False
return doc
nlp.add_pipe(set_custom_boundaries, before="parser")
doc = nlp(text)
for sent in doc.sents:
print(sent.text)
推荐阅读
- woocommerce - 在产品标题下方的 Woocommerce 中显示产品属性
- c# - 仅使用 Linq(EF 核心)选择特定字段
- php - 在值输入复选框中传递特殊字符
- javascript - 用来自对象的值填充嵌套名称的输入
- python - 将循环中的数组保存在列中的一个 txt 文件中
- java - spring batch 随机访问一个文件实现二分查找
- node.js - 如何整合Mongoosastic?
- vue.js - vue-apollo:GraphQL 查询仅在使用时运行
标签。永远不会在脚本代码中工作。this.$apollo.queries 为空 - c# - 如何让 Web 应用程序从不同的服务器提供静态文件
- php - 向 QueryBuilder 添加自定义字段时,有什么方法可以防止 Doctrine 结果嵌套实体?