POS-Tagger非常慢

dis*_*ame 7 python nlp nltk pos-tagger

nltk用来从句子中生成n-gram,首先删除给定的停用词.但是,nltk.pos_tag()我的CPU(Intel i7)的速度极慢,最长需要0.6秒.

输出:

['The first time I went, and was completely taken by the live jazz band and atmosphere, I ordered the Lobster Cobb Salad.']
0.620481014252
["It's simply the best meal in NYC."]
0.640982151031
['You cannot go wrong at the Red Eye Grill.']
0.644664049149
Run Code Online (Sandbox Code Playgroud)

代码:

for sentence in source:

    nltk_ngrams = None

    if stop_words is not None:   
        start = time.time()
        sentence_pos = nltk.pos_tag(word_tokenize(sentence))
        print time.time() - start

        filtered_words = [word for (word, pos) in sentence_pos if pos not in stop_words]
    else:
        filtered_words = ngrams(sentence.split(), n)
Run Code Online (Sandbox Code Playgroud)

这真的很慢还是我在这里做错了什么?

alv*_*vas 9

使用pos_tag_sents用于标记多个句子:

>>> import time
>>> from nltk.corpus import brown
>>> from nltk import pos_tag
>>> from nltk import pos_tag_sents
>>> sents = brown.sents()[:10]
>>> start = time.time(); pos_tag(sents[0]); print time.time() - start
0.934092998505
>>> start = time.time(); [pos_tag(s) for s in sents]; print time.time() - start
9.5061340332
>>> start = time.time(); pos_tag_sents(sents); print time.time() - start 
0.939551115036
Run Code Online (Sandbox Code Playgroud)


小智 6

nltk pos_tag is defined as:
from nltk.tag.perceptron import PerceptronTagger
def pos_tag(tokens, tagset=None):
    tagger = PerceptronTagger()
    return _pos_tag(tokens, tagset, tagger)
Run Code Online (Sandbox Code Playgroud)

因此,对pos_tag的每次调用都会实例化感知器模块,这需要花费大量的计算时间.您可以通过直接调用tagger.tag来节省这段时间:

from nltk.tag.perceptron import PerceptronTagger
tagger=PerceptronTagger()
sentence_pos = tagger.tag(word_tokenize(sentence))
Run Code Online (Sandbox Code Playgroud)