1

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}

EdBoi4
  • 21
  • 4
  • `if letter.isdigit():`? – B Remmelzwaal Mar 07 '23 at 16:26
  • Are you looking to count the frequency of individual digits (from 0 to 9) or would you process consecutive digits in the string as distinct numbers ? Also, please format your code properly so it all appears in the grey box. A sample input and expected output would also help us help you. – Alain T. Mar 07 '23 at 16:28
  • Yes. I'm looking to count the frequency of the individual digits. I will add the sample I/O now – EdBoi4 Mar 07 '23 at 16:33
  • 1
    Please, remove your refactoring tag. You want to change the functionality of your code, that is not [refactor](https://en.wikipedia.org/wiki/Code_refactoring). – Jorge Luis Mar 07 '23 at 16:33
  • Change `for int in text:` to `for letter in text` and `if letter in string.ascii_letters` to `if letter in string.digits`. You also don't need the .lower() conversion. – Alain T. Mar 07 '23 at 16:38
  • Thank you Alain T. That should fix it – EdBoi4 Mar 07 '23 at 16:43

1 Answers1

1

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) )
Alain T.
  • 40,517
  • 4
  • 31
  • 51