NLTK中的FreqDist没有排序输出

时间:2014-04-13 12:23:56

标签: python nlp nltk

我是Python的新手,我正在尝试自学语言处理。 python中的NLTK有一个名为FreqDist的函数,它可以给出文本中单词的频率,但由于某些原因它无法正常工作。

本教程是我写的:

fdist1 = FreqDist(text1)
vocabulary1 = fdist1.keys()
vocabulary1[:50]

所以基本上它应该给我一个文本中最常用的50个单词的列表。但是,当我运行代码时,结果是最不频繁到最频繁的50个最少频繁的单词,而不是相反。我得到的输出如下:

[u'succour', u'four', u'woods', u'hanging', u'woody', u'conjure', u'looking', u'eligible', u'scold', u'unsuitableness', u'meadows', u'stipulate', u'leisurely', u'bringing', u'disturb', u'internally', u'hostess', u'mohrs', u'persisted', u'Does', u'succession', u'tired', u'cordially', u'pulse', u'elegant', u'second', u'sooth', u'shrugging', u'abundantly', u'errors', u'forgetting', u'contributed', u'fingers', u'increasing', u'exclamations', u'hero', u'leaning', u'Truth', u'here', u'china', u'hers', u'natured', u'substance', u'unwillingness...]

我正在完全复制教程,但我一定是做错了。

以下是教程的链接:

http://www.nltk.org/book/ch01.html#sec-computing-with-language-texts-and-words

示例位于标题"图1.3:计算出现在文本中的单词(频率分布)"

有谁知道我怎么解决这个问题?

4 个答案:

答案 0 :(得分:35)

来自NLTK's GitHub

  

NLTK3中的FreqDist是collections.Counter的包装器; Counter提供most_common()方法按顺序返回项目。 FreqDist.keys()方法由标准库提供;它没有被覆盖。我认为我们与stdlib的兼容性很好。

      googlecode上的文档非常陈旧,它们来自2011年。可以在http://nltk.org网站上找到更多最新文档。

因此,对于NLKT版本3而不是fdist1.keys()[:50],请使用fdist1.most_common(50)

tutorial也已更新:

fdist1 = FreqDist(text1)
>>> print(fdist1)
<FreqDist with 19317 samples and 260819 outcomes>
>>> fdist1.most_common(50)
[(',', 18713), ('the', 13721), ('.', 6862), ('of', 6536), ('and', 6024),
('a', 4569), ('to', 4542), (';', 4072), ('in', 3916), ('that', 2982),
("'", 2684), ('-', 2552), ('his', 2459), ('it', 2209), ('I', 2124),
('s', 1739), ('is', 1695), ('he', 1661), ('with', 1659), ('was', 1632),
('as', 1620), ('"', 1478), ('all', 1462), ('for', 1414), ('this', 1280),
('!', 1269), ('at', 1231), ('by', 1137), ('but', 1113), ('not', 1103),
('--', 1070), ('him', 1058), ('from', 1052), ('be', 1030), ('on', 1005),
('so', 918), ('whale', 906), ('one', 889), ('you', 841), ('had', 767),
('have', 760), ('there', 715), ('But', 705), ('or', 697), ('were', 680),
('now', 646), ('which', 640), ('?', 637), ('me', 627), ('like', 624)]
>>> fdist1['whale']
906

答案 1 :(得分:6)

作为使用FreqDist的替代方法,您只需使用来自`集合的Counter,另请参阅https://stackoverflow.com/questions/22952069/how-to-get-the-rank-of-a-word-from-a-dictionary-with-word-frequencies-python/22953416#22953416

>>> from collections import Counter
>>> text = """foo foo bar bar foo bar hello bar hello world  hello world hello world hello world  hello world hello hello hello"""
>>> dictionary = Counter(text.split())
>>> dictionary
{"foo":3, "bar":4, "hello":9, "world":5}
>>> dictionary.most_common()
[('hello', 9), ('world', 5), ('bar', 4), ('foo', 3)]
>>> [i[0] for i in dictionary.most_common()]
['hello', 'world', 'bar', 'foo']

答案 2 :(得分:4)

这个答案很老。请改用this answer

为了解决此问题,我建议您执行以下步骤:

<强> 1。检查您使用的nltk版本:

>>> import nltk
>>> print nltk.__version__
2.0.4  # preferably 2.0 or higher

较早版本的nltk没有可排序的FreqDist.keys方法。

<强> 2。确认您没有无意中修改了text1vocabulary1

打开一个新shell并从头开始重新开始该过程:

>>> from nltk.book import *
*** Introductory Examples for the NLTK Book ***
Loading text1, ..., text9 and sent1, ..., sent9
Type the name of the text or sentence to view it.
Type: 'texts()' or 'sents()' to list the materials.
text1: Moby Dick by Herman Melville 1851
text2: Sense and Sensibility by Jane Austen 1811
text3: The Book of Genesis
text4: Inaugural Address Corpus
text5: Chat Corpus
text6: Monty Python and the Holy Grail
text7: Wall Street Journal
text8: Personals Corpus
text9: The Man Who Was Thursday by G . K . Chesterton 1908
>>> from nltk import FreqDist
>>> fdist1 = FreqDist(text1)
>>> vocabulary1 = fdist1.keys()
>>> vocabulary1[:50]
[',', 'the', '.', 'of', 'and', 'a', 'to', ';', 'in', 'that', "'", '-', 'his', 'it', 'I', 's', 'is', 'he', 'with', 'was', 'as', '"', 'all', 'for', 'this', '!', 'at', 'by', 'but', 'not', '--', 'him', 'from', 'be', 'on', 'so', 'whale', 'one', 'you', 'had', 'have', 'there', 'But', 'or', 'were', 'now', 'which', '?', 'me', 'like']

请注意,vocabulary1不应包含字符串u'succour'(原始帖子输出中的第一个unicode字符串):

>>> vocabulary1.count(u'succour')  # vocabulary1 does **not** contain the string u'succour'
0

第3。如果您仍然遇到问题,请检查您的源代码和文本列表,以确保它们符合您在下面看到的内容

>>> import inspect
>>> print inspect.getsource(FreqDist.keys)  # make sure your source code matches the source code below
    def keys(self):
        """
        Return the samples sorted in decreasing order of frequency.

        :rtype: list(any)
        """
        self._sort_keys_by_value()
        return map(itemgetter(0), self._item_cache)

>>> print inspect.getsource(FreqDist._sort_keys_by_value)  # and matches this source code
    def _sort_keys_by_value(self):
        if not self._item_cache:
            self._item_cache = sorted(dict.items(self), key=lambda x:(-x[1], x[0]))  # <= check this line especially

>>> text1[:40]  # does the first part of your text list match this one?
['[', 'Moby', 'Dick', 'by', 'Herman', 'Melville', '1851', ']', 'ETYMOLOGY', '.', '(', 'Supplied', 'by', 'a', 'Late', 'Consumptive', 'Usher', 'to', 'a', 'Grammar', 'School', ')', 'The', 'pale', 'Usher', '--', 'threadbare', 'in', 'coat', ',', 'heart', ',', 'body', ',', 'and', 'brain', ';', 'I', 'see', 'him']

>>> text1[-40:]  # and what about the end of your text list?
['second', 'day', ',', 'a', 'sail', 'drew', 'near', ',', 'nearer', ',', 'and', 'picked', 'me', 'up', 'at', 'last', '.', 'It', 'was', 'the', 'devious', '-', 'cruising', 'Rachel', ',', 'that', 'in', 'her', 'retracing', 'search', 'after', 'her', 'missing', 'children', ',', 'only', 'found', 'another', 'orphan', '.']

如果您的源代码或文本列表与上述内容完全不符,请考虑使用最新的稳定版本重新安装nltk

答案 3 :(得分:1)

import nltk
fdist1 = nltk.FreqDist(text)

fdist1包含“键”-用于单词,“值”-用于单词的频率计数。

上面的变量fdist1没有排序,因此不会根据命令显示前50个结果。请使用以下代码首先对其进行排序:

fdist1 = sorted(fdist1 , key = freq_dist.__getitem__, reverse = True)
fdist1[0:50]

这将打印出前50个常用词。