人工智能

自然语言处理NLP(Spacy)入门 (一)

2020-10-17  本文已影响0人  生信编程日常

自然语言处理(Natuarl Language Processing, NLP),是人工智能领域的一个重要的方向。一般我们听到的文本分类、文本挖掘都属于NLP的范畴。


为了完成NLP任务,我们一般需要对文本进行预处理。预处理一般包括文本清洗、分词、去掉停用词、标准化和特征提取等(不过现在BERT横空出世,甚至可以不经过这些步骤)。Spacy是这个领域内的一个比较领先好用的工业级处理库。

导入英文处理库:

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

分词(Tokenizing):

doc = nlp("Tea is healthy and calming, don't you think?")
for token in doc:
    print(token)

输出:

Tea
is
healthy
and
calming
,
do
n't
you
think
?

词形还原 (Lemmatization) 和判断停用词:
(用token.lemma_与token.is_stop方法)

print(f"Token \t\tLemma \t\tStopword".format('Token', 'Lemma', 'Stopword'))
print("-"*40)
for token in doc:
    print(f"{str(token)}\t\t{token.lemma_}\t\t{token.is_stop}")

输出:

Token       Lemma       Stopword
----------------------------------------
Tea     tea     False
is      be      True
healthy     healthy     False
and     and     True
calming     calm        False
,       ,       False
do      do      True
n't     not     True
you     -PRON-      True
think       think       False
?       ?       False

可以看到is的词形被还原为了be,某些词的原形其实是一样的,处理的时候应该按照一样的文本处理,比如:

doc = nlp('help helped cup cups')
for token in doc:
    print(token.lemma_)

输出:

help
help
cup
cup
上一篇下一篇

猜你喜欢

热点阅读