我正在尝试使用max来查找输出python CFD字典中关键字的最高值。我被这个网站(https://www.hallada.net/2017/07/11/generating-random-poems-with-python.html)误导,相信最大值可以用来正确地找到cfd值。然而,我发现当CFD字典中的条目频率发生变化时,似乎没有得到正确的结果。
我是python的新手,我想我可能只是对如何调用数据感到困惑。我试着对列表进行排序,相信我可以将键中的值排序,但我想我也不太明白如何做到这一点。
words = ('The quick brown fox jumped over the '
'lazy the lazy the lazy dog and the quick cat').split(' ')
from collections import defaultdict
cfd = defaultdict(lambda: defaultdict(lambda: 0))
for i in range(len(words) - 2): # loop to the next-to-last word
cfd[words[i].lower()][words[i+1].lower()] += 1
{k: dict(v) for k, v in dict(cfd).items()}
max(cfd['the'])" The“后面最常见的单词是”lazy“。但是,python会输出CFD字典中的最后一个单词,即“last”。
发布于 2019-11-07 04:11:03
你的问题是cfd' the‘是一个字典,当max对它进行原始迭代时,它实际上只是在对键进行迭代。在这种情况下,“快速”大于“懒惰”,因为字符串。
将最大值更改为:max(cfd['the'].items(), key=lambda x: x[1])
https://stackoverflow.com/questions/58737555
复制相似问题