简体   繁体   中英

Counting the number of letter characters in a string

I need to have a user enter a string in which any character is allowed. Once entered I need to count each letter character occurrence in the string. So far I have:

s = input("Enter a string: ")
s = s.upper()
all_freq = {}
for i in s:
    if i in all_freq:
        all_freq[i] += 1
    else:
        all_freq[i] = 1
print(all_freq)

This is wrong because it includes numbers, spaces and special characters in the count.

Using a list comprehension to filter and Counter (from collections) to count would make it more compact:

from collections import Counter
s = "Hello World!" 
result = Counter(c for c in s.upper() if c.isalpha())
print(result)
# Counter({'L': 3, 'O': 2, 'H': 1, 'E': 1, 'W': 1, 'R': 1, 'D': 1})

If you only want to count characters, you can use the isalpha function to check if a character is alphabetical.

s = input("Enter a string: ")
s = s.upper()
all_freq = {}
for i in s:
    if i.isalpha():
        if i in all_freq:
            all_freq[i] += 1
        else:
            all_freq[i] = 1
print(all_freq)
Enter a string: Hello World!
{'H': 1, 'E': 1, 'L': 3, 'O': 2, 'W': 1, 'R': 1, 'D': 1}

Hope this helps!

Maybe one simple solution is to use string module like bellow:

import string

s = input("Enter a string: ")
ignore = string.whitespace + string.digits + string.punctuation
s = s.upper()
all_freq = {}

for c in s:
    if c not in ignore:
        all_freq[c] = all_freq.get(c, 0) + 1
print(all_freq)

You can also use regex expression to check for characters

import re
s = input("Enter a string: ")
s = s.upper()
all_freq = {}
for i in s:
   if bool(re.match('[A-Z]',i)):
       if i in all_freq :
          all_freq[i] += 1
       else:
          all_freq[i] = 1
print(all_freq)

Here's the output:

Enter a string: hello hello 1 $
{'H': 2, 'E': 2, 'L': 4, 'O': 2}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM