2017-04-24 24 views
1

输入:“我最喜欢的游戏是使命召唤。”如何将关键字放入NLTK标记大小?

我设置为“使命召唤”作为重点词,这句话将成为记号化过程中的一个字。

最后要得到的结果:“我的”,“收藏”,“游戏”,“是”,“使命召唤”]

那么,如何设置在python NLP关键字?

+3

为什么它会是一个令牌?你希望它被识别为一个实体,而不是一个令牌。 – erip

回答

2

我认为你想要的是关键字提取,你可以做到这一点,例如首先用每个单词的PoS标签标记每个单词,然后在PoS标签上应用某种正则表达式将有趣的单词加入到关键字句中。

import nltk 
from nltk import pos_tag 
from nltk import tokenize 

def extract_phrases(my_tree, phrase): 
    my_phrases = [] 
    if my_tree.label() == phrase: 
     my_phrases.append(my_tree.copy(True)) 

    for child in my_tree: 
     if type(child) is nltk.Tree: 
      list_of_phrases = extract_phrases(child, phrase) 
      if len(list_of_phrases) > 0: 
       my_phrases.extend(list_of_phrases) 

    return my_phrases 


def main(): 
    sentences = ["My favorite game is call of duty"] 

    grammar = "NP: {<DT>?<JJ>*<NN>|<NNP>*}" 
    cp = nltk.RegexpParser(grammar) 

    for x in sentences: 
     sentence = pos_tag(tokenize.word_tokenize(x)) 
     tree = cp.parse(sentence) 
     print "\nNoun phrases:" 
     list_of_noun_phrases = extract_phrases(tree, 'NP') 
     for phrase in list_of_noun_phrases: 
      print phrase, "_".join([x[0] for x in phrase.leaves()]) 

if __name__ == "__main__": 
    main() 

这将输出如下:

Noun phrases: 
(NP favorite/JJ game/NN) favorite_game 
(NP call/NN) call 
(NP duty/NN) duty 

但是,你可以玩弄

grammar = "NP: {<DT>?<JJ>*<NN>|<NNP>*}" 

尝试其他类型的表达式,这样就可以得到你想要的东西,取决于你想加入的单词/标签。

此外,如果你有兴趣,看看这个非常好的介绍的关键词/词语的提取:

https://bdewilde.github.io/blog/2014/09/23/intro-to-automatic-keyphrase-extraction/

0

这,当然,太晚要到OP是有用的,但我想我倒是在这里把这个答案的人:

这听起来像你也许真的问的是:如何确保复合短语,如‘使命召唤’得到组合在一起作为一个令牌?

您可以使用NLTK的多字表达标记生成器,像这样:

string = 'My favorite game is call of duty' 
tokenized_string = nltk.word_tokenize(string) 

mwe = [('call', 'of', 'duty')] 
mwe_tokenizer = nltk.tokenize.MWETokenizer(mwe) 
tokenized_string = mwe_tokenizer.tokenize(tokenized_string) 

mwe代表多字表达。的tokenized_string值将是['My', 'favorite', 'game', 'is', 'call of duty']