35

我是 spacy 的新手,我想使用它的 lemmatizer 功能,但我不知道如何使用它,就像我进入单词字符串一样,它将以单词的基本形式返回字符串。

例子:

  • '单词'=> '单词'
  • “做过”=>“做”

谢谢你。

4

5 回答 5

71

以前的答案很复杂,无法编辑,所以这里有一个更传统的答案。

# make sure your downloaded the english model with "python -m spacy download en"

import spacy
nlp = spacy.load('en')

doc = nlp(u"Apples and oranges are similar. Boots and hippos aren't.")

for token in doc:
    print(token, token.lemma, token.lemma_)

输出:

Apples 6617 apples
and 512 and
oranges 7024 orange
are 536 be
similar 1447 similar
. 453 .
Boots 4622 boot
and 512 and
hippos 98365 hippo
are 536 be
n't 538 not
. 453 .

来自官方灯光之旅

于 2017-03-24T15:48:06.653 回答
25

如果您只想使用 Lemmatizer,您可以通过以下方式执行此操作:

from spacy.lemmatizer import Lemmatizer
from spacy.lang.en import LEMMA_INDEX, LEMMA_EXC, LEMMA_RULES

lemmatizer = Lemmatizer(LEMMA_INDEX, LEMMA_EXC, LEMMA_RULES)
lemmas = lemmatizer(u'ducks', u'NOUN')
print(lemmas)

输出

['duck']

更新

自 spacy 2.2 版以来,LEMMA_INDEX、LEMMA_EXC 和 LEMMA_RULES 已被捆绑到一个Lookups对象中:

import spacy
nlp = spacy.load('en')

nlp.vocab.lookups
>>> <spacy.lookups.Lookups object at 0x7f89a59ea810>
nlp.vocab.lookups.tables
>>> ['lemma_lookup', 'lemma_rules', 'lemma_index', 'lemma_exc']

您仍然可以直接将词形还原器与单词和 POS(词性)标签一起使用:

from spacy.lemmatizer import Lemmatizer, ADJ, NOUN, VERB

lemmatizer = nlp.vocab.morphology.lemmatizer
lemmatizer('ducks', NOUN)
>>> ['duck']

您可以像上面一样将 POS 标签作为导入的常量传递,也可以作为字符串传递:

lemmatizer('ducks', 'NOUN')
>>> ['duck']

从 spacy.lemmatizer 导入 Lemmatizer、ADJ、名词、动词

于 2018-02-23T13:08:16.557 回答
11

代码 :

import os
from spacy.en import English, LOCAL_DATA_DIR

data_dir = os.environ.get('SPACY_DATA', LOCAL_DATA_DIR)

nlp = English(data_dir=data_dir)

doc3 = nlp(u"this is spacy lemmatize testing. programming books are more better than others")

for token in doc3:
    print token, token.lemma, token.lemma_

输出 :

this 496 this
is 488 be
spacy 173779 spacy
lemmatize 1510965 lemmatize
testing 2900 testing
. 419 .
programming 3408 programming
books 1011 book
are 488 be
more 529 more
better 615 better
than 555 than
others 871 others

示例参考:这里

于 2016-08-04T14:46:18.100 回答
5

我使用 Spacy 2.x 版

import spacy
nlp = spacy.load('en_core_web_sm', disable=['parser', 'ner'])
doc = nlp('did displaying words')
print (" ".join([token.lemma_ for token in doc]))

和输出:

do display word

希望能帮助到你 :)

于 2020-04-19T04:56:37.750 回答
-2

我用了:

import spacy

nlp = en_core_web_sm.load()
doc = nlp("did displaying words")
print(" ".join([token.lemma_ for token in doc]))
>>> do display word

但它回来了

OSError: [E050] Can't find model 'en_core_web_sm'. It doesn't seem to be a shortcut link, a Python package or a valid path to a data directory.

我用了:

pip3 install https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-2.2.0/en_core_web_sm-2.2.0.tar.gz

摆脱错误。

于 2020-08-30T09:48:49.507 回答