-2

Using regex, I wanna count the specific letter. I made a match object like below. but don't know how to count its frequency. Most of counting examples were for words so I could not find good reference for it.

f = open("C:\Python27\test.txt")
raw_sentence = f.read
upper_sentence = raw_sentence.upper()
match = re.findall(r"A", upper_sentence)

Should I make some list data just like other word counting codes do?

roadrunner66
  • 7,772
  • 4
  • 32
  • 38
Youngin Na
  • 87
  • 7
  • The title is about letter and description is about word, which one is it? Having example input and expected output would be helpful too. – niemmi May 08 '16 at 05:41
  • sorry it was letter. And the result that I want is like "A : 3", "B : 6" like this – Youngin Na May 08 '16 at 05:46
  • Possible duplicate from yesterday: [How can I get histogram number with pairs by using python code?](http://stackoverflow.com/questions/37084670/how-can-i-get-histogram-number-with-pairs-by-using-python-code/) – John1024 May 08 '16 at 05:51

1 Answers1

1

Just use str.count:

raw_sentence.upper().count('A')

If you want counts of multiple elements, its better to use collections.Counter:

>>> s = 'abcabcsdab'
>>> import collections
>>> collections.Counter(s)
Counter({'a': 3, 'b': 3, 'c': 2, 'd': 1, 's': 1})
heemayl
  • 39,294
  • 7
  • 70
  • 76