gpt4 book ai didi

python - 使用 get 与 get() 在 NLTK 中对 FreqDist 进行排序

转载 作者:太空宇宙 更新时间:2023-11-04 10:12:37 24 4
gpt4 key购买 nike

我正在玩弄 NLTK 和模块 freqDist

import nltk
from nltk.corpus import gutenberg
print(gutenberg.fileids())
from nltk import FreqDist
fd = FreqDist()

for word in gutenberg.words('austen-persuasion.txt'):
fd[word] += 1

newfd = sorted(fd, key=fd.get, reverse=True)[:10]

所以我在玩 NLTK,对排序部分有疑问。当我像这样运行代码时,它会正确排序 freqDist 对象。但是,当我使用 get() 而不是 get 运行它时,我遇到了错误

Traceback (most recent call last):
File "C:\Python34\NLP\NLP.py", line 21, in <module>
newfd = sorted(fd, key=fd.get(), reverse=True)[:10]
TypeError: get expected at least 1 arguments, got 0

为什么 get 正确而 get() 错误。我的印象是 get() 应该是正确的,但我想它不是。

最佳答案

本质上,NLTK中的FreqDist对象是原生Python的collections.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)]

像字典一样,您可以遍历 Counter 对象,它会返回键:

>>> [key for key in c]
['a', 'c', 'b', 'd']
>>> c.keys()
['a', 'c', 'b', 'd']

您还可以使用 .items() 函数获取键及其值的元组:

>>> 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 vs .get()的问题,前者是函数本身,后者是需要函数的实例字典的键作为参数:

>>> 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() 时,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')

关于python - 使用 get 与 get() 在 NLTK 中对 FreqDist 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37427673/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com