你可以使用 nltk
、Textblob
、SpaCy
或其他许多库来取得好的结果。这些库都可以胜任工作,但效率不同。
import nltk
from textblob import TextBlob
import spacy
nlp = spacy.load('en')
nlp1 = spacy.load('en_core_web_lg')
txt = """Natural language processing (NLP) is a field of computer science, artificial intelligence, and computational linguistics concerned with the interactions between computers and human (natural) languages."""
在我的Windows 10 2核心、4处理器、8GB RAM的i5 惠普 笔记本电脑上,在Jupyter Notebook中,我进行了一些比较,并得出了以下结果。
对于TextBlob:
%%time
print([w for (w, pos) in TextBlob(txt).pos_tags if pos[0] == 'N'])
输出结果为
>>> ['language', 'processing', 'NLP', 'field', 'computer', 'science', 'intelligence', 'linguistics', 'inter', 'actions', 'computers', 'languages']
Wall time: 8.01 ms #average over 20 iterations
对于nltk:
%%time
print([word for (word, pos) in nltk.pos_tag(nltk.word_tokenize(txt)) if pos[0] == 'N'])
输出结果为
>>> ['language', 'processing', 'NLP', 'field', 'computer', 'science', 'intelligence', 'linguistics', 'inter', 'actions', 'computers', 'languages']
Wall time: 7.09 ms #average over 20 iterations
对于Spacy:
%%time
print([ent.text for ent in nlp(txt) if ent.pos_ == 'NOUN'])
输出结果为
>>> ['language', 'processing', 'field', 'computer', 'science', 'intelligence', 'linguistics', 'inter', 'actions', 'computers', 'languages']
Wall time: 30.19 ms #average over 20 iterations
似乎
nltk
和
TextBlob
更快,这是可以预料的,因为它们不存储有关输入文本
txt
的其他信息。而
Spacy
则慢得多。还有一件事。在处理
NLP
时
SpaCy
错过了名词,而
nltk
和
TextBlob
却成功识别了它。除非我需要从输入的
txt
中提取其他信息,否则我会选择
nltk
或
TextBlob
。查看有关
spacy
的快速入门,请单击
此处。查看有关
TextBlob
的基础知识,请单击
此处。查看
nltk
的操作指南,请单击
此处。
if pos.startswith('NN'):
,同时使用set
或collections.Counter
,不要保留列表。并且使用一些map/reduce代替列表推导式。否则,请尝试使用“浅层解析”(shallow parsing),也称为“块分析”(chunking)。 - alvas