web-dev-qa-db-ja.com

NLTKのFreqDistが出力をソートしない

私はPythonに不慣れで、言語処理を自分で学ぼうとしています。pythonのNLTKには、FreqDistという関数があります。テキストですが、何らかの理由で正しく機能していません。

これは私がチュートリアルに書いたものです:

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

つまり、基本的には、テキストで最も頻繁に使用される50の単語のリストを提供することになっています。ただし、コードを実行すると、結果は50leastの頻度の高い単語で、頻度の低いものから高いものの順になります。 。私が得ている出力は次のとおりです。

[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:テキストに表示される単語のカウント(度数分布)」という見出しのすぐ下にあります。

誰かが私がこれを修正する方法を知っていますか?

11
user3528925

この答えは古いです。代わりに この回答 を使用してください。

この問題のトラブルシューティングを行うには、次の手順を実行することをお勧めします。

1。使用しているnltkのバージョンを確認してください

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

古いバージョンのnltkには、並べ替え可能なFreqDist.keysメソッドがありません。

2。 text1またはvocabulary1を誤って変更していないことを確認してください。

新しいシェルを開き、プロセスを最初からやり直します。

>>> 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を最新の安定バージョンで再インストールすることを検討してください。

から NLTKのGitHub

NLTK3のFreqDistは、collections.Counterのラッパーです。 Counterは、アイテムを順番に返すためのmost_common()メソッドを提供します。 FreqDist.keys()メソッドは標準ライブラリによって提供されます。オーバーライドされません。 stdlibとの互換性が向上しているのは良いことだと思います。

googlecodeのドキュメントは非常に古く、2011年のものです。最新のドキュメントは http://nltk.org Webサイトにあります。

したがって、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
38
Hugo

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']
7
alvas
import nltk
fdist1 = nltk.FreqDist(text)

fdist1には、単語の場合は「キー」、単語の頻度カウントの場合は「値」が含まれます。

上記の変数fdist1はソートされていないため、コマンドに基づいて上位50件の結果を出力しません。最初にそれらをソートするには、次のコードを使用してください。

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

これにより、上位50の頻繁な単語が出力されます。

2