对于NLTK
3.1版,里面
nltk/tag/__init__.py,
pos_tag是这样定义的:
from nltk.tag.perceptron import PerceptronTaggerdef pos_tag(tokens, tagset=None): tagger = PerceptronTagger() return _pos_tag(tokens, tagset, tagger)
因此,每次对
pos_tagfirst的调用实例化
PerceptronTagger都会花费一些时间,因为它涉及加载pickle文件。
_pos_tag
只需调用
tagger.tagwhen
tagset是
None。因此,您可以通过
一次 加载文件并调用
tagger.tag自己而不是调用来节省一些时间
pos_tag:
from nltk.tag.perceptron import PerceptronTaggertagger = PerceptronTagger() def __remove_stop_words(self, tokenized_text, stop_words, tagger=tagger): sentences_pos = tagger.tag(tokenized_text) filtered_words = [word for (word, pos) in sentences_pos if pos not in stop_words and word not in stop_words] return filtered_words
pos_tag_sents使用与上述相同的技巧-实例化
PerceptronTagger一次,然后调用
_pos_tag多次。因此,使用上述代码,您将获得与重构和调用相当的性能提升
pos_tag_sents。
另外,如果
stop_words列表很长,则可以通过
stop_words设置以下设置节省一些时间:
stop_words = set(stop_words)
因为检查集合中的成员资格(例如
pos not instop_words)是一项
O(1)(恒定时间)操作,而检查列表中的成员资格是一项
O(n)操作(即,它需要的时间与列表的长度成比例地增加)。



