1

I'm trying to create a program which outputs how many times a specific character was used.

For example, if the sentence is I like bikes! The output should be:

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

However my program does this

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

So its doubling up the letters.

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

How can I fix this?

joaquin
  • 82,968
  • 29
  • 138
  • 152
Paul Shan
  • 63
  • 1
  • 8

4 Answers4

1

Instead of going through all the characters in text, go through all the characters in the alphabet, but report only those that are present:

def count_char(text):
    for char in string.ascii_letters:
        count = text.count(char)
        if count:
            print(char + ' = ' + str(count))
DYZ
  • 55,249
  • 10
  • 64
  • 93
  • I get an error with this though. "string is not defined". What about if I wanted to count characters, instead of just letters. So like numbers and symbols? – Paul Shan Aug 05 '18 at 06:59
  • Well, you should import the missing module. It also has collections of digits and other stuff you may want to count. – DYZ Aug 05 '18 at 07:00
1

I suggest initializing a dictionary and updating the values as you run the for loop

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

this should give you the desired answer

DYZ
  • 55,249
  • 10
  • 64
  • 93
  • How can I print it nicely though, like how I printed it? It prints it in a mess. Like {h: 1, e: 2.... – Paul Shan Aug 05 '18 at 07:13
  • https://stackoverflow.com/questions/26660654/how-do-i-print-the-key-value-pairs-of-a-dictionary-in-python – DYZ Aug 05 '18 at 07:58
0

If you want your output it ordered, you can derive a class from OrderedDict and Counter. If order does not matter, you can use Counter directly (as suggested by @user3483203 in a comment to your question).

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))

Output:

I = 1
l = 1
i = 2
k = 2
e = 2
b = 1
s = 1
! = 1
Mike Scotty
  • 10,530
  • 5
  • 38
  • 50
0

You can try this:

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!')

the output is:

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

as expected.

Elementary
  • 1,443
  • 1
  • 7
  • 17