如何在python NLTK中使用正则表达式退避标记来覆盖NN?

时间:2013-02-10 20:52:31

标签: python nlp nltk pos-tagger

我一直在使用自定义训练的nltk pos_tagger,有时我得到明显的动词(以ING或ED结尾)作为NN进入。如何通过额外的regexpTagger让tagger处理所有NN只是为了找到额外的动词?

我已经为次要正则表达式标记包含了一些示例代码。

from nltk.tag.sequential import RegexpTagger

rgt = RegexpTagger(
    (r'.*ing$', 'VBG'),                # gerunds
    (r'.*ed$', 'VBD'),                 # past tense verbs
])

由于

1 个答案:

答案 0 :(得分:0)

这是tri_gram标记器,它由bi-gram(由uni-gram支持)支持,主要的后退tragger是正则表达式tragger。因此,如果任何其他标记器未能根据此处定义的规则对其进行标记,则此处的最后一个标记将留给正则表达式。希望这可以帮助您构建自己的规则的正则表达式标记。

   from nltk.corpus import brown
   import sys
   from nltk import pos_tag
   from nltk.tokenize import word_tokenize
   import nltk
   from nltk import ne_chunk
   def tri_gram():
   ##Trigram tagger done by training data from brown corpus 
    b_t_sents=brown.tagged_sents(categories='news')

   ##Making n-gram tagger using Turing backoff
   default_tagger = nltk.RegexpTagger(
            [(r'^-?[0-9]+(.[0-9]+)?$', 'CD'),   # cardinal numbers
         (r'(The|the|A|a|An|an)$', 'AT'),   # articles
         (r'.*able$', 'JJ'),                # adjectives
         (r'.*ness$', 'NN'),                # nouns formed from adjectives  
         (r'.*ly$', 'RB'),                  # adverbs
         (r'.*s$', 'NNS'),                  # plural nouns  
         (r'.*ing$', 'VBG'),                # gerunds   
         (r'.*ed$', 'VBD'),                 # past tense verbs
         (r'.*', 'NN')                      # nouns (default)
        ])
    u_gram_tag=nltk.UnigramTagger(b_t_sents,backoff=default_tagger) 
    b_gram_tag=nltk.BigramTagger(b_t_sents,backoff=u_gram_tag)
    t_gram_tag=nltk.TrigramTagger(b_t_sents,backoff=b_gram_tag)

    ##pos of given text
    f_read=open(sys.argv[1],'r')
    given_text=f_read.read();
    segmented_lines=nltk.sent_tokenize(given_text) 
    for text in segmented_lines:
        words=word_tokenize(text)
        sent = t_gram_tag.tag(words)
        print ne_chunk(sent)
tri_gram()