问题描述
我正在尝试在spacy的管道上创建一个自定义组件。我想将文字转换为较低的文字。
我的代码:
nlp = spacy.load('en_core_web_sm')
def lower_component(doc):
doc.text = doc.text.lower
return doc
nlp.add_pipe(lower_component,first=True)
print('Pipeline:',nlp.pipe_names)
doc = nlp("Hello World!")
doc
AttributeError:“ spacy.tokens.doc.Doc”对象的属性“文本”不可写
解决方法
spaCy的核心原则之一是spaCy的处理过程永远不会修改文本本身。如果要小写文本,则应在调用nlp(text)
之前在spacy之外运行的预处理步骤中。
我发现了!只要通过一堂课:
class Lower(object):
name = "Lower"
nlp: Language
def __init__(self,nlp: Language):
self.nlp = nlp
def __call__(self,doc: Doc) -> Doc:
text = doc.text
return self.nlp.make_doc(text.lower())
及以下:
nlp.add_pipe(Lower(nlp),first=True)