基本的に、NLTK
でFreqDist
オブジェクトはネイティブのPythonのcollections.Counter
のサブクラスで、それでは、どのようにCounter
が作品を見てみましょう:Counter
はそのキーとして、リスト内の要素を格納した辞書である
値などの要素の数:
>>> from collections import Counter
>>> Counter(['a','a','b','c','c','c','d'])
Counter({'c': 3, 'a': 2, 'b': 1, 'd': 1})
>>> c = Counter(['a','a','b','c','c','c','d'])
その頻度によってソートされた要素のリストを取得するには、.most_common()
機能を使用することができ、それがカウントによって並べ替え要素とその数のタプルを返します。
>>> c.most_common()
[('c', 3), ('a', 2), ('b', 1), ('d', 1)]
そして逆に:
あなたはカウンターオブジェクトを反復処理することができ、それが鍵を返します辞書のよう
>>> list(reversed(c.most_common()))
[('d', 1), ('b', 1), ('a', 2), ('c', 3)]
:あなたはまたに.items()
機能を使用することができます
>>> [key for key in c]
['a', 'c', 'b', 'd']
>>> c.keys()
['a', 'c', 'b', 'd']
キーとその値のタプルを取得します。
>>> c.items()
[('a', 2), ('c', 3), ('b', 1), ('d', 1)]
また、あなただけTranspose/Unzip Function (inverse of zip)?見、その数によって並べ替えのキーが必要な場合:
>>> k, v = zip(*c.most_common())
>>> k
('c', 'a', 'b', 'd')
が戻っ.get()
対.get
の質問に行く、前者は関数自体で、後者はのインスタンスである一方、そのパラメータとして、辞書のキーを必要とする関数:sorted()
を呼び出すとき
>>> c = Counter(['a','a','b','c','c','c','d'])
>>> c
Counter({'c': 3, 'a': 2, 'b': 1, 'd': 1})
>>> c.get
<built-in method get of Counter object at 0x7f5f95534868>
>>> c.get()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: get expected at least 1 arguments, got 0
>>> c.get('a')
2
、sorted
関数内key=...
パラメータがあるでないソートするリスト/辞書のキーですが、sorted
はソートに使用するキーです。
したがって、これらが同じであるが、彼らは唯一のキーの値を返す:
>>> [c.get(key) for key in c]
[2, 3, 1, 1]
>>> [c[key] for key in c]
[2, 3, 1, 1]
ソートされる時、値をソートするための基準として使用されているので、これらは同じ出力を実現:
>>> sorted(c, key=c.get)
['b', 'd', 'a', 'c']
>>> v, k = zip(*sorted((c.get(key), key) for key in c))
>>> list(k)
['b', 'd', 'a', 'c']
>>> sorted(c, key=c.get, reverse=True) # Highest to lowest
['c', 'a', 'b', 'd']
>>> v, k = zip(*reversed(sorted((c.get(key), key) for key in c)))
>>> k
('c', 'a', 'd', 'b')
ほとんどの場合、必要なのは 'fd.most_common()'です。基本的に、NLTKのFreqDistはコレクションです.Counter、http:// stackoverflowを参照してください。com/questions/34603922/pythons-collections-counter-and-nltk-probability-freqdist/34606637#34606637 – alvas
よろしくお願いします。 – alvas