ale*_*cxe 7 python nlp document spacy
我有一个较长的文本被解析Spacy为一个Doc实例:
import spacy
nlp = spacy.load('en_core_web_lg')
doc = nlp(content)
Run Code Online (Sandbox Code Playgroud)
doc这里成为一个Doc类实例。
现在,由于文本很大,因此我想仅使用文档的一部分(例如前100个句子)在Jupyter笔记本中进行处理,实验和可视化。
如何Doc从现有文档的一部分中切片并创建新实例?
在对象as_doc()上使用更好的解决方案Span(https://spacy.io/api/span#as_doc):
nlp = spacy.load('en_core_web_lg')
content = "This is my sentence. And here's another one."
doc = nlp(content)
for i, sent in enumerate(doc.sents):
print(i, "a", sent, type(sent))
doc_sent = sent.as_doc()
print(i, "b", doc_sent, type(doc_sent))
Run Code Online (Sandbox Code Playgroud)
给出输出:
0 a This is my sentence. <class 'spacy.tokens.span.Span'>
0 b This is my sentence. <class 'spacy.tokens.doc.Doc'>
1 a And here's another one. <class 'spacy.tokens.span.Span'>
1 b And here's another one. <class 'spacy.tokens.doc.Doc'>
Run Code Online (Sandbox Code Playgroud)
(为了清晰起见,完整写出代码片段 - 当然可以进一步缩短)
实现目的的一种相当丑陋的方法是构建一个句子列表并从句子的子集构建一个新文档。
sentences = [sent.string.strip() for sent in doc.sents][:100]
minidoc = nlp(' '.join(sentences))
Run Code Online (Sandbox Code Playgroud)
感觉应该有更好的解决方案,但我想这至少有效。