如果您正在使用Python 2.7或更高您可以使用collections.Counter。
的Python 2.7+
>>> import collections
>>> s = "I want to count frequencies."
>>> counter = collections.Counter(s)
>>> counter
Counter({' ': 4, 'e': 3, 'n': 3, 't': 3, 'c': 2, 'o': 2, 'u': 2, 'a': 1, 'f': 1, 'I': 1, 'q': 1, 'i': 1, 's': 1, 'r': 1, 'w': 1, '.': 1})
>>> n = sum(counter.values()) * 1.0 # Convert to float so division returns float.
>>> n
28
>>> [(char, count/n) for char, count in counter.most_common()]
[(' ', 0.14285714285714285), ('e', 0.10714285714285714), ('n', 0.10714285714285714), ('t', 0.10714285714285714), ('c', 0.07142857142857142), ('o', 0.07142857142857142), ('u', 0.07142857142857142), ('a', 0.03571428571428571), ('f', 0.03571428571428571), ('I', 0.03571428571428571), ('q', 0.03571428571428571), ('i', 0.03571428571428571), ('s', 0.03571428571428571), ('r', 0.03571428571428571), ('w', 0.03571428571428571), ('.', 0.03571428571428571)]
的Python 3+
>>> import collections
>>> s = "I want to count frequencies."
>>> counter = collections.Counter(s)
>>> counter
Counter({' ': 4, 'e': 3, 'n': 3, 't': 3, 'c': 2, 'o': 2, 'u': 2, 'a': 1, 'f': 1, 'I': 1, 'q': 1, 'i': 1, 's': 1, 'r': 1, 'w': 1, '.': 1})
>>> n = sum(counter.values())
>>> n
28
>>> [(char, count/n) for char, count in counter.most_common()]
[(' ', 0.14285714285714285), ('e', 0.10714285714285714), ('n', 0.10714285714285714), ('t', 0.10714285714285714), ('c', 0.07142857142857142), ('o', 0.07142857142857142), ('u', 0.07142857142857142), ('a', 0.03571428571428571), ('f', 0.03571428571428571), ('I', 0.03571428571428571), ('q', 0.03571428571428571), ('i', 0.03571428571428571), ('s', 0.03571428571428571), ('r', 0.03571428571428571), ('w', 0.03571428571428571), ('.', 0.03571428571428571)]
這也將在按頻率的降序返回(炭,頻率)元組。
什麼是IntArrayToText調用?它是一個字符串嗎? – 2011-05-08 03:48:52