Counting characters in a sentence
我正在尝试创建一个输出特定字符使用次数的程序。
例如,如果句子是
输出应该是:
1 2 3 4 5 6 7 8 | I = 1 l = 1 i = 2 k = 2 e = 2 b = 1 s = 1 ! = 1 |
但是我的程序会这样做
1 2 3 4 5 6 7 8 9 10 11 | I = 1 l = 1 i = 2 k = 1 e = 2 b = 1 i = 2 k = 2 e = 2 s = 1 ! = 1 |
所以它加倍了字母。
1 2 3 4 | def count_char(text): for char in text: count = text.count(char) print(char + ' = ' + str(count)) |
我怎样才能解决这个问题?
我建议在运行for循环时初始化字典并更新值
1 2 3 4 5 6 7 8 | def count_char(text): answer={} for char in text: if char in answer: answer[char]+=1 else: answer[char]=1 print(answer) |
这应该给你想要的答案
不要遍历文本中的所有字符,而是遍历字母表中的所有字符,但仅报告存在的字符:
1 2 3 4 5 | def count_char(text): for char in string.ascii_letters: count = text.count(char) if count: print(char + ' = ' + str(count)) |
你可以试试这个:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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!') |
输出是:
1 2 3 4 5 6 7 8 | I = 1 l = 1 i = 2 k = 2 e = 2 b = 1 s = 1 ! = 1 |
正如所料。
如果您想要输出它的输出,可以从
1 2 3 4 5 6 7 8 9 10 11 12 | 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)) |
输出:
1 2 3 4 5 6 7 8 | I = 1 l = 1 i = 2 k = 2 e = 2 b = 1 s = 1 ! = 1 |