Skip to main content
 首页 » 编程设计

Python 和 NLTK : Baseline tagger

2024年11月01日9soundcode

我正在为基线标注器编写代码。基于 Brown 语料库,它为单词分配了最常见的标签。因此,如果单词“works”被标记为动词 23 次,被标记为复数名词 30 次,那么根据用户输入的句子,它会被标记为复数名词。如果在语料库中找不到该词,则默认将其标记为名词。 到目前为止,我的代码会返回单词的每个标签,而不仅仅是最常见的标签。如何实现只返回每个单词的频繁标记?

import nltk  
from nltk.corpus import brown 
 
def findtags(userinput, tagged_text): 
    uinput = userinput.split() 
    fdist = nltk.FreqDist(tagged_text) 
    result = [] 
    for item in fdist.items(): 
        for u in uinput: 
            if u==item[0][0]: 
                t = (u,item[0][1]) 
                result.append(t) 
        continue 
        t = (u, "NN") 
        result.append(t) 
    return result 
 
def main(): 
    tags = findtags("the quick brown fox", brown.tagged_words()) 
    print tags 
 
if __name__ == '__main__': 
    main() 

请您参考如下方法:

如果是英语,NLTK 中有一个默认的词性标注器,很多人一直在提示它,但这是一个很好的快速修复(更像是创可贴而不是扑热息痛),请参阅 POS tagging - NLTK thinks noun is adjective :

>>> from nltk.tag import pos_tag 
>>> from nltk.tokenize import word_tokenize 
>>> sent = "the quick brown fox" 
>>> pos_tag(word_tokenize(sent)) 
[('the', 'DT'), ('quick', 'NN'), ('brown', 'NN'), ('fox', 'NN')] 

如果您想从头开始训练基线标注器,我建议您按照这样的示例进行操作,但将语料库更改为英语:https://github.com/alvations/spaghetti-tagger

通过像 spaghetti-tagger 一样构建一个 UnigramTagger,您应该自动为每个单词实现最常见的标记。

但是,如果你想用非机器学习的方式来做,首先要计算 word:POS,你需要的是某种类型的标记比率。另见 Part-of-speech tag without context using nltk :

from nltk.tag import pos_tag 
from nltk.tokenize import word_tokenize 
from collections import Counter, defaultdict 
from itertools import chain 
 
def type_token_ratio(documentstream): 
    ttr = defaultdict(list) 
    for token, pos in list(chain(*documentstream)): 
        ttr[token].append(pos)   
    return ttr 
 
def most_freq_tag(ttr, word): 
    return Counter(ttr[word]).most_common()[0][0] 
 
sent1 = "the quick brown fox quick me with a quick ." 
sent2 = "the brown quick fox fox me with a brown ."  
documents = [sent1, sent2] 
 
# Calculates the TTR. 
documents_ttr = type_token_ratio([pos_tag(word_tokenize(i)) for i in documents]) 
 
# Best tag for the word. 
print Counter(documents_ttr['quick']).most_common()[0] 
 
# Best tags for a sentence 
print [most_freq_tag(documents_ttr, i) for i in sent1.split()] 

注意:文档流可以定义为句子列表,其中每个句子包含带有/不带标签的标记列表。