首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >不排序输出的NLTK中的FreqDist

不排序输出的NLTK中的FreqDist
EN

Stack Overflow用户
提问于 2014-04-13 12:23:56
回答 4查看 24.3K关注 0票数 14

我是Python新手,我正在努力教自己语言处理。python中的NLTK有一个名为FreqDist的函数,它给出了文本中单词的频率,但由于某种原因,它不能正常工作。

这是本教程让我写的:

代码语言:javascript
运行
复制
fdist1 = FreqDist(text1)
vocabulary1 = fdist1.keys()
vocabulary1[:50]

所以基本上,它应该给我一个名单,50个最常见的单词在课文。但是,当我运行代码时,结果是50个最不频繁的单词排序为“最频繁”,而不是“最频繁”。我得到的输出如下:

代码语言:javascript
运行
复制
[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:计算出现在文本中的单词(频率分布)”下面。

有人知道我该怎么解决这个问题吗?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2014-04-13 12:59:19

这个答案已经过时了。使用这个答案代替。

为了解决这个问题,我建议采取以下步骤:

检查正在使用的nltk 的的哪个版本

代码语言:javascript
运行
复制
>>> import nltk
>>> print nltk.__version__
2.0.4  # preferably 2.0 or higher

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

验证您是否无意中修改了text1 vocabulary1

打开一个新的shell,从一开始就重新启动该进程:

代码语言:javascript
运行
复制
>>> 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字符串):

代码语言:javascript
运行
复制
>>> vocabulary1.count(u'succour')  # vocabulary1 does **not** contain the string u'succour'
0

如果您仍然有问题,请检查源代码和文本列表,以确保它们与您在下面看到的内容相匹配。

代码语言:javascript
运行
复制
>>> 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

票数 6
EN

Stack Overflow用户

发布于 2014-12-13 23:50:38

来自NLTK's GitHub

FreqDist in NLTK3是collections.Counter的包装器;Counter提供了按顺序返回项的most_common()方法。FreqDist.keys()方法由标准库提供;它不被重写。我认为这是好的,我们正在变得更加兼容stdlib。 googlecode的博士很老,他们是从2011年开始的。更多最新的文档可以在http://nltk.org网站上找到.

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

教程还得到了更新:

代码语言:javascript
运行
复制
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
票数 40
EN

Stack Overflow用户

发布于 2014-04-13 20:06:18

作为使用FreqDist的另一种选择,您可以简单地使用“集合”中的Counter,也可以参见https://stackoverflow.com/questions/22952069/how-to-get-the-rank-of-a-word-from-a-dictionary-with-word-frequencies-python/22953416#22953416

代码语言:javascript
运行
复制
>>> 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']
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23042699

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档