Shi*_*rma 9 python language-detection spacy
每次我运行在 Kaggle 上找到的以下代码时,我都会得到ValueError. 这是因为SpaCy新版本 v3 的缘故:
import scispacy
import spacy
import en_core_sci_lg
from spacy_langdetect import LanguageDetector
nlp = en_core_sci_lg.load(disable=["tagger", "ner"])
nlp.max_length = 2000000
nlp.add_pipe(LanguageDetector(), name='language_detector', last=True)
Run Code Online (Sandbox Code Playgroud)
ValueError: [E966]nlp.add_pipe现在采用已注册组件工厂的字符串名称,而不是可调用组件。预期为字符串,但在 0x00000216BB4C8D30> 处获得 <spacy_langdetect.spacy_langdetect.LanguageDetector 对象(名称:“language_detector”)。
如果您使用以下命令创建组件nlp.create_pipe('name'):删除 nlp.create_pipe 并nlp.add_pipe('name')改为调用。
如果您传入类似TextCategorizer(): 的组件,请使用字符串名称进行调用nlp.add_pipe,例如nlp.add_pipe('textcat').
如果您使用自定义组件:将装饰器@Language.component(对于函数组件)或@Language.factory(对于类组件/工厂)添加到自定义组件并为其指定一个名称,例如@Language.component('your_name')。然后您可以运行nlp.add_pipe('your_name')将其添加到管道中。
我已经安装了这些版本:
python_version : 3.8.5
spacy.version : '3.0.3'
scispacy.version : '0.4.0'
en_core_sci_lg.version : '0.4.0'
Run Code Online (Sandbox Code Playgroud)
Nic*_*uti 10
您还可以使用@Language.factory装饰器以更少的代码实现相同的结果:
import scispacy
import spacy
import en_core_sci_lg
from spacy_langdetect import LanguageDetector
from spacy.language import Language
@Language.factory('language_detector')
def language_detector(nlp, name):
return LanguageDetector()
nlp = en_core_sci_lg.load(disable=["tagger", "ner"])
nlp.max_length = 2000000
nlp.add_pipe('language_detector', last=True)
Run Code Online (Sandbox Code Playgroud)
v3 中的工作方式add_pipe发生了变化;组件必须注册,然后只需使用它们的名称即可将其添加到管道中。在这种情况下,您必须像这样包装 LanguageDetector:
import scispacy
import spacy
import en_core_sci_lg
from spacy_langdetect import LanguageDetector
from spacy.language import Language
def create_lang_detector(nlp, name):
return LanguageDetector()
Language.factory("language_detector", func=create_lang_detector)
nlp = en_core_sci_lg.load(disable=["tagger", "ner"])
nlp.max_length = 2000000
nlp.add_pipe('language_detector', last=True)
Run Code Online (Sandbox Code Playgroud)
您可以在spaCy 文档中阅读有关其工作原理的更多信息。