基于换行符的空格自定义句子切分 [英] Spacy custom sentence segmentation on line break

查看:48
本文介绍了基于换行符的空格自定义句子切分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将this文档拆分成段落。具体地说,只要有换行符(<br>)

,我就想拆分文本

这是我正在使用的代码,但没有产生我希望的结果

nlp = spacy.load("en_core_web_lg")

def set_custom_boundaries(doc):
    for token in doc[:-1]:
        if token.text == "<br>":
            doc[token.i+1].is_sent_start = True
    return doc

nlp.add_pipe(set_custom_boundaries, before="parser")
doc = nlp(text)
print([sent.text for sent in doc.sents])

可以使用NLTK's TextTilingTokenizer实现类似的解决方案,但要检查Spacy内是否有类似的解决方案

推荐答案

您差不多到了,但问题是默认令牌化器在‘<;’和‘>’上拆分,因此条件token.text == "<br>"永远不为真。我会在<br>前后添加空格。例如

import spacy
from spacy.symbols import ORTH


def set_custom_boundaries(doc):
    for token in doc[:-1]:
        if token.text == "<br>":
            doc[token.i+1].is_sent_start = True
    return doc

nlp = spacy.load("en_core_web_sm")
text = "the quick brown fox<br>jumps over the lazy dog"
text = text.replace('<br>', ' <br> ')
special_case = [{ORTH: "<br>"}]
nlp.tokenizer.add_special_case("<br>", special_case)

nlp.add_pipe(set_custom_boundaries, first=True)
doc = nlp(text)
print([sent.text for sent in doc.sents])

再来看看这张PR,合并到Master后,就不再需要用空格换行了。

https://github.com/explosion/spaCy/pull/4259

这篇关于基于换行符的空格自定义句子切分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆