How can I refactor this code to return the frequency of numbers instead of frequency of characters?

Question:

I saw this Python code to show frequency of characters and I would like it to return frequency of strings but I am unable to do it right

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

print(count_numbers("This is a sentence."))
#Should be {}

print(count_numbers("55 North Center Drive"))
#Should be {‘5’: 2}

Asked By: EdBoi4

||

Answers:

You could use the Counter class from the collections modules. A Counter() is a special kind of dictionary that counts instances of the keys you give it. You can use the filter function to extract only the digits out of the text.

from collections import Counter

text =  "55 North Center Drive"
result = Counter(filter(str.isdigit,text)) 
print(result)

Counter({'5': 2})

If you don’t want to use a library, you can do the same thing with a normal dictionary:

result = dict()
result.update( (d,result.get(d,0)+1) for d in filter(str.isdigit,text) )
Answered By: Alain T.
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.