2015-10-17 124 views
0

我已经编写了这个Python程序来计算Python字符串中每个字符的数量。如何计算Python字符串中每个字符的数量?

def count_chars(s): 
    counts = [0] * 65536 
    for c in s: 
     counts[ord(c)] += 1 
    return counts 

def print_counts(counts): 
    for i, n in enumerate(counts): 
     if n > 0: 
      print(chr(i), '-', n) 

if __name__ == '__main__': 
    print_counts(count_chars('hello, world \u2615')) 

输出:

- 2 
, - 1 
d - 1 
e - 1 
h - 1 
l - 3 
o - 2 
r - 1 
w - 1 
☕ - 1 

这个程序可以采取计数任何Unicode字符的任何出现次数的照顾?如果没有,可以做些什么来确保每个可能的Unicode字符都被照顾?

+0

你试试,看看会发生什么? – usr2564301

回答

7

您的代码只能处理Basic Multilingual Plane中的字符;例如,emoticons将不会被处理。您可以通过使用字典而不是具有固定数量索引的列表来弥补这一点,并将字符用作关键字。

然而,你应该只使用一个collections.Counter() object

from collections import Counter 

counts = Counter(s) 

for character, count in counts.most_common(): 
    print(character, '-', count) 

它,毕竟,设计了这样的用例。

演示:

>>> from collections import Counter 
>>> s = 'hello, world \u2615 \U0001F60A' 
>>> counts = Counter(s) 
>>> for character, count in counts.most_common(): 
...  print(character, '-', count) 
... 
    - 3 
l - 3 
o - 2 
r - 1 
w - 1 
e - 1 
h - 1 
d - 1 
☕ - 1 
, - 1 
- 1 
相关问题