我正在尝试添加一个异常来识别">>"和">>"作为开始新句子的指示器。例如
import spacy
nlp = spacy.load('en_core_web_sm')
doc = nlp(u'>> We should. >>No.')
for sent in doc.sents:
print (sent)
它打印出:
>> We should.
>
>
No.
但是,我希望它打印出来:
>> We should.
>> No.
提前感谢您抽出宝贵时间!
您需要创建自定义组件。代码示例提供了一个自定义句子分割示例。在文档中,该示例执行以下操作:
添加管道组件以禁止句子边界的示例 在某些令牌之前。
代码(根据您的需要调整示例(:
import spacy
def prevent_sentence_boundaries(doc):
for token in doc:
if not can_be_sentence_start(token):
token.is_sent_start = False
return doc
def can_be_sentence_start(token):
if token.i > 0 and token.nbor(-1).text == '>':
return False
return True
nlp = spacy.load('en_core_web_sm')
nlp.add_pipe(prevent_sentence_boundaries, before='parser')
raw_text = u'>> We should. >> No.'
doc = nlp(raw_text)
sentences = [sent.string.strip() for sent in doc.sents]
for sentence in sentences:
print(sentence)
输出
>> We should.
>> No.