gpt4 book ai didi

python - 如何将字符串转换成字典,并统计每个单词的个数

转载 作者:太空狗 更新时间:2023-10-30 01:42:12 25 4
gpt4 key购买 nike

我只是想知道我将如何转换一个字符串,例如“hello there hi there”,并将它变成一个字典,然后使用这个字典,我想计算字典中每个单词的数量,并返回它按字母顺序排列。所以在这种情况下它会返回:

[('hello', 1), ('hi', 1), ('there', 2)]

任何帮助将不胜感激

最佳答案

>>> from collections import Counter
>>> text = "hello there hi there"
>>> sorted(Counter(text.split()).items())
[('hello', 1), ('hi', 1), ('there', 2)]

class collections.Counter([iterable-or-mapping])

A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.

关于python - 如何将字符串转换成字典,并统计每个单词的个数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16557900/

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