【问题标题】:FreqDist with nltk: ValueError: too many values to unpack带有 nltk 的 FreqDist:ValueError:要解压的值太多
【发布时间】:2013-11-14 10:31:07
【问题描述】:

我一直在尝试找出给定句子中名词的频率分布。如果我这样做:

text = "This ball is blue, small and extraordinary. Like no other ball."
text=text.lower()
token_text= nltk.word_tokenize(text)
tagged_sent = nltk.pos_tag(token_text)
nouns= []
for word,pos in tagged_sent:
    if pos in ['NN',"NNP","NNS"]:
        nouns.append(word)
freq_nouns=nltk.FreqDist(nouns)
print freq_nouns

它考虑“球”和“球”。作为单独的词。所以我继续tokenized the sentence before tokenizing the words

text = "This ball is blue, small and extraordinary. Like no other ball."
text=text.lower()
sentences = nltk.sent_tokenize(text)                        
words = [nltk.word_tokenize(sent)for sent in sentences]    
tagged_sent = [nltk.pos_tag(sent)for sent in words]
nouns= []
for word,pos in tagged_sent:
    if pos in ['NN',"NNP","NNS"]:
        nouns.append(word)
freq_nouns=nltk.FreqDist(nouns)
print freq_nouns

它给出了以下错误:

Traceback (most recent call last):
File "C:\beautifulsoup4-4.3.2\Trial.py", line 19, in <module>
for word,pos in tagged_sent:
ValueError: too many values to unpack

我做错了什么?请帮忙。

【问题讨论】:

    标签: python-2.7 nltk frequency-distribution


    【解决方案1】:

    你离得太近了!

    在这种情况下,由于您的列表理解 tagged_sent = [nltk.pos_tag(sent)for sent in words],您将 tagged_sent 从元组列表更改为元组列表。

    您可以执行以下操作来了解您拥有的对象类型:

    >>> type(tagged_sent), len(tagged_sent)
    (<type 'list'>, 2)
    

    这表明您有一个列表;在这种情况下是 2 个句子。您可以像这样进一步检查其中一个句子:

    >>> type(tagged_sent[0]), len(tagged_sent[0])
    (<type 'list'>, 9)
    

    你可以看到第一句话是另一个列表,包含9个项目。那么,其中一件物品是什么样子的?好吧,让我们看看第一个列表的第一项:

    >>> tagged_sent[0][0]
    ('this', 'DT')
    

    如果您想看到整个对象(我经常这样),您可以询问pprint(漂亮打印)模块,以便看起来像这样更好:

    >>> from pprint import pprint
    >>> pprint(tagged_sent)
    [[('this', 'DT'),
      ('ball', 'NN'),
      ('is', 'VBZ'),
      ('blue', 'JJ'),
      (',', ','),
      ('small', 'JJ'),
      ('and', 'CC'),
      ('extraordinary', 'JJ'),
      ('.', '.')],
     [('like', 'IN'), ('no', 'DT'), ('other', 'JJ'), ('ball', 'NN'), ('.', '.')]]
    

    所以,长答案是您的代码需要遍历新的第二层列表,如下所示:

    nouns= []
    for sentence in tagged_sent:
        for word,pos in sentence:
            if pos in ['NN',"NNP","NNS"]:
                nouns.append(word)
    

    当然,这只是返回一个非唯一的项目列表,如下所示:

    >>> nouns
    ['ball', 'ball']
    

    您可以通过多种不同方式唯一化此列表,但您可以使用set() 数据结构快速实现,如下所示:

    unique_nouns = list(set(nouns))
    >>> print unique_nouns
    ['ball']
    

    要了解其他可以唯一化项目列表的方法,请参阅稍旧但非常有用的方法:http://www.peterbe.com/plog/uniqifiers-benchmark

    【讨论】:

    • 谢谢 :) 我需要非唯一列表来计算单词的频率 :)
    猜你喜欢
    • 1970-01-01
    • 2012-09-27
    • 2010-12-01
    • 2015-01-17
    相关资源
    最近更新 更多