Search code examples
pythoncharnumberscoursera-api

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


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}


Solution

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