计算句子中的字符

时间:2018-08-05 06:53:13

标签: python function for-loop count

我正在尝试创建一个程序,该程序输出使用特定字符的次数。

例如,如果句子是I like bikes! 输出应为:

I = 1
l = 1
i = 2
k = 2
e = 2
b = 1
s = 1
! = 1

但是我的程序会这样做

I = 1
l = 1
i = 2
k = 1
e = 2
b = 1
i = 2
k = 2
e = 2
s = 1
! = 1

因此将字母加倍。

def count_char(text):
    for char in text:
        count = text.count(char)
        print(char + ' = ' + str(count))

我该如何解决?

4 个答案:

答案 0 :(得分:1)

代替遍历文本中的所有字符,而是遍历字母表中的所有字符,而仅报告存在的那些字符:

Vue.nextTick(function () {
   var offsetHeight = document.getElementById('filterSection').offsetHeight;
   var x = document.getElementsByClassName("searchResultSection");
   x[0].style.maxHeight = "calc(100% - ${offsetHeight}px)";
});

答案 1 :(得分:1)

我建议在运行for循环时初始化字典并更新值

def count_char(text):
    answer={}
    for char in text:
        if char in answer:
           answer[char]+=1
        else:
           answer[char]=1
    print(answer)

这应该给您想要的答案

答案 2 :(得分:0)

如果要对输出进行排序,则可以从OrderedDictCounter派生一个类。如果顺序无关紧要,则可以直接使用Counter(如@ user3483203在对问题的评论中建议的那样)。

from collections import OrderedDict, Counter

class OrderedCounter(Counter, OrderedDict):
    pass

s = "I like bikes!"

c = OrderedCounter(s)

for char, count in c.items():
    if char.strip(): # skip blanks
        print(char + ' = ' + str(count))

输出:

I = 1
l = 1
i = 2
k = 2
e = 2
b = 1
s = 1
! = 1

答案 3 :(得分:0)

您可以尝试以下方法:

def char_counter_printer(string):
    if type(string) is not str:
        return False
    else:
        chardict={}
        charlist=[]
        for char in string:
            try:
                chardict[char]+=1
            except:
                chardict[char]=1
                charlist.append(char)

    for ch in charlist:
        if(ch.strip()):
            print(ch,'=',chardict[ch])


char_counter_printer('I Like bikes!')

输出为:

I = 1
L = 1
i = 2
k = 2
e = 2
b = 1
s = 1
! = 1

符合预期。