簡體   English   中英

如何計算Python字符串中每個字符的數量?

[英]How can I count the number of each character in a Python string?

我已經編寫了這個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字符都得到處理?

您的代碼僅處理基本多語言平面中的字符; 例如, 表情符號將不被處理。 您可以通過僅使用字典而不是具有固定索引數的列表來解決此問題,並使用字符作為鍵。

但是,您應該只使用collections.Counter()對象

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
message='alpha beta gamma sudama'
z = list(message)
p = []
for x in range (0,len(z)):
    y=0
    i=0
    count=0
    if z[x] not in p:
        p.append(z[x])
        while i < len(z) :
            if z[x] == z[i]:
                count = count+1
            i = i+1
        print(z[x],count)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM