简体   繁体   中英

Count the frequency of letters in a string, not blank spaces, numbers, or punctuation

def count_letters(text):
  result = {}
  # Go through eactter in the text
  for letter in text:
    # Check if the letter needs to be counted or not
    if letter in text:
       result[letter.lower()]=result.get(letter,0)+1
    # Add or increment the value in the dictionary
  for k  in result:
    return result

print(count_letters("AaBbCc"))
# Should be {'a': 2, 'b': 2, 'c': 2}

print(count_letters("Math is fun! 2+2=4"))
# Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1}

print(count_letters("This is a sentence."))
# Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}

You can use Counter with filter .

import string
from collections import Counter
Counter(filter(lambda x:x in string.ascii_letters,_str.lower()))

Counter({'m': 1,
         'a': 1,
         't': 1,
         'h': 1,
         'i': 1,
         's': 1,
         'f': 1,
         'u': 1,
         'n': 1})

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