计算Python字符串中出现的字符数

2024-04-24 02:38:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我想得到给定句子中每个字符的计数。我尝试了下面的代码,得到了每个字符的计数,但它在输出中显示了重复的字符数。如何删除重复字符。在

def countwords(x):
    x=x.lower()
    for i in x:
        print(i,'in',x.count(i)) 

x=str(input("Enter a paragraph "))
countwords(x)

我的输出是:

enter image description here

我的输出不应包含空格计数和重复字符。。怎么办。。。。!!!在


Tags: 代码inforinputdefcount字符lower
3条回答

用口述

def countwords(x):
    d = dict()
    x=x.lower()
    for i in x:
        if i in d.keys():
            d[i] = d[i] +1;
        else:
             d[i] = 1;

     for i in d.keys():
          print i + " " + d[i]

有几种不同的方法,大多数是在jonrsharpe的评论中暗示的,但是我建议使用一个简单的^{}。在

set方法以及其他一些方法如下:

# An approach using a set
def countwords_set(s):
    for c in set(s):
        if c == ' ': continue
        print(c, 'in', s.count(c))

# An approach using a standard dict
def countwords_dict(s):
    d = dict()
    for c in s:
        if c == ' ': continue               # Skip spaces
        d[c] = d.get(c,0) + 1               # Use the .get method in case the 
                                            #   key isn't set

    for c,x in d.items():                   # Display results
        print(c, 'in', x)


# An approach using a defaultdict (from the collections module)
def countwords_ddict(s):
    from collections import defaultdict     # Typically, imports go at the top

    d = defaultdict(int)

    for c in s:
        if c == ' ': continue
        d[c] += 1

    for c,x in d.items():
        print(c, 'in', x)


# An approach using a Counter (from the collections module)
def countwords_counter(s):
    from collections import Counter         # Typically, imports go at the top

    counter = Counter(s)

    # Counters can be accessed like dicts
    for c,x in counter.items():
        if c == ' ': continue
        print(c, 'in', x)


# User input and comparison
s = str(input("Enter a paragraph "))
s = s.lower()

countwords_set(s)
print(" -")

countwords_dict(s)
print(" -")

countwords_ddict(s)
print(" -")

countwords_counter(s)
print(" -")

对于每种方法,输出基本上是相同的,尽管字符的顺序可能不同,因为Python字典是无序的。在

检查此代码:

my_string = "count a character occurance"
my_list = list(my_string)
print (my_list)
get_unique_char = set(my_list)
print (get_unique_char)

for key in get_unique_char:
    print (key, my_string.count(key))

相关问题 更多 >