【问题标题】:Python: How to count pos tags from from a sentence?Python:如何从一个句子中计算 pos 标签?
【发布时间】:2014-01-06 22:48:28
【问题描述】:

我有来自这个link 的代码。它返回 POS 标签及其出现次数。 我将如何实现一个代码,而不是输入一个标签,而是输入一个句子,它会返回其中的单词以及基于语料库(在本例中为 Brown 语料库)的每个单词的不同 pos 标签。

def findtags(tag_prefix, tagged_text):
    cfd = nltk.ConditionalFreqDist((tag, word) for (word, tag) in tagged_text
                                  if tag.startswith(tag_prefix))
    return dict((tag, cfd[tag].keys()[:5]) for tag in cfd.conditions())

tagdictNNS = findtags('NNS', nltk.corpus.brown.tagged_words())

for tag in sorted(tagdictNNS):
    print tag, tagdictNNS[tag]

for k,v in tagdictNNS.items():
        new[k] = len(tagdictNNS[k])

print new

【问题讨论】:

    标签: python nlp nltk tagging


    【解决方案1】:
    >>>from nltk.tag import pos_tag
    >>>from nltk.tokenize import word_tokenize
    
    >>>sent = "This is a foo bar sentence."
    >>>text= pos_tag(word_tokenize(sent))
    >>>print(text)
    
    >>>from collections import Counter
    >>>count= Counter([j for i,j in pos_tag(word_tokenize(sent))])
    >>>print (count)
    

    【讨论】:

    • 一些 cmets 会很有用。
    【解决方案2】:

    如果是英文的,你可以试试这个:

    >>> from nltk.tag import pos_tag
    >>> from nltk.tokenize import word_tokenize
    >>> sent = "This is a foo bar sentence."
    >>> pos_tag(word_tokenize(sent))
    [('This', 'DT'), ('is', 'VBZ'), ('a', 'DT'), ('foo', 'NN'), ('bar', 'NN'), ('sentence', 'NN'), ('.', '.')]
    >>> from collections import Counter
    >>> Counter([j for i,j in pos_tag(word_tokenize(sent))])
    Counter({'NN': 3, 'DT': 2, 'VBZ': 1, '.': 1})
    

    NLTK 有一个用于 word tokenizationnltk.tokenize.word_tokenizePOS tagging (nltk.tag.pos_tag) 的内置模块,它使用 Penn Treebank 标签。然后您可以简单地将 pos 标签列表从标记的句子输入到Counter.

    如果您想将标点符号分组到单个PUNCT 标签中,您可以试试这个:

    >>> import string
    >>> Counter([k if k not in string.punctuation else "PUNCT" for k in [j for i,j in pos_tag(word_tokenize(sent))]])
    Counter({'NN': 3, 'DT': 2, 'VBZ': 1, 'PUNCT': 1})
    

    【讨论】:

      【解决方案3】:

      the documentation(靠近页面底部)中有一个可能相关的示例:

      nltk.tag 定义了几个标记器,它们接受一个标记列表(通常是一个句子),为每个标记分配一个标记,并返回标记标记的结果列表。大多数标注器都是基于训练语料库自动构建的。例如,UnigramTagger 通过检查训练语料库中 w 最常见的标签来标记每个单词 w:

      from nltk.corpus import brown
      from nltk.tag import UnigramTagger
      tagger = UnigramTagger(brown.tagged_sents(categories='news')[:500])
      sent = ['Mitchell', 'decried', 'the', 'high', 'rate', 'of', 'unemployment']
      for word, tag in tagger.tag(sent):
          print(word, '->', tag)
      

      这给出了:

      Mitchell -> NP
      decried -> None
      the -> AT
      high -> JJ
      rate -> NN
      of -> IN
      unemployment -> None
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多