2015-10-17 164 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 
相關問題