def word_count(str):
counts = dict()
words = str.split()
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
return counts
print(word_count("""the quick brown fox jumps over the lazy lazy lazy dog."""))
输出:
{'the': 2, 'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1, 'over': 1, 'lazy': 3, 'dog.': 1}
但是我想要两个输出,一个像这样:
{3 : 'lazy',2 :'the',1 : 'quick',1 : 'brown',1 : 'fox',1 : 'jumps',1 : 'over',1 : 'dog'}
这样的另一个按字母顺序组织:
['brown' : 1,'dog.' : 1,'fox' : 1,'jumps' 1: ,'lazy' 3: , 'over': 1,'quick' 1: ,'the' : 2]
我知道排序后可以按字母顺序组织,但我不知道如何将其与结果一起插入。我到处都在寻找Stack-overflow和其他地方,以查看是否可以找到任何结果,但找不到任何东西。
如果有人帮助我,我将非常感激。谢谢:)
您可以通过word_count
的结果执行类似的操作>
res = word_count("""the quick brown fox jumps over the lazy lazy lazy dog.""")
word_list = list(r.items())
by_word = sorted(word_list, key=lambda t: t[1], reverse = True)
by_count = [t[::-1] for t in by_word]
print(by_word)
print(by_count)
正如其他人所说,您想要的结果无效,因为它们无效。但是,如果您想要与您提供的最终示例匹配的排序集,则可以使用类似以下的内容。