上这样做
所以我有一个句子,说
一个人走进酒吧,要求1.4根啤酒。调酒师说:"我必须额外向您收取费用,那是一个生啤酒浮动"。那家伙说:"在这种情况下,最好将其变成双重。
我知道我可能必须使用正则表达式或其他东西,并确保我基于空格而备用,以便单独完成每个单词。
另外,我正在尝试在Python 3.
最简单的是Counter
。然后,您可以对其项目进行排序:
>>> from collections import Counter
>>> c = Counter(s)
>>> for char, num in sorted(c.items()):
... print(repr(char), num)
' ' 25
'"' 2
"'" 2
',' 1
'.' 2
'1' 1
'4' 1
'A' 1
'I' 1
'T' 1
'a' 13
'b' 4
'c' 1
# ...
您可以使用collections.Counter
:
from collections import Counter
s = 'A guy walks into a bar and asks for 1.4 root beers. The bartender says "Ill have to charge you extra, thats a root beer float". The guy says "In that case, better make it a double.'
frequencies = Counter(list(s))
new_data = sorted(frequencies.items())
print(new_data)
输出:
[(' ', 36), ('"', 3), (',', 2), ('.', 4), ('1', 1), ('4', 1), ('A', 1), ('I', 2), ('T', 2), ('a', 18), ('b', 6), ('c', 2), ('d', 3), ('e', 16), ('f', 2), ('g', 3), ('h', 6), ('i', 2), ('k', 3), ('l', 5), ('m', 1), ('n', 4), ('o', 10), ('r', 11), ('s', 10), ('t', 14), ('u', 4), ('v', 1), ('w', 1), ('x', 1), ('y', 5)]