-2

So I need to loop through a sentence character by character and total up the different letters and how many times they occur. I can't think of a way of doing the first bit (I'll do the totalling up myself I have a good enough idea and I'd like to see if I can do it solo). I'm not top notch at Python but I assume it'll be a

for letter in sentence

but I'm not sure how to loop through each letter.

DonnellyOverflow
  • 3,085
  • 4
  • 21
  • 34
  • Do you mean through each word? You can't iterate over `"a"` (well you can, but it would be a bit pointless). – rlms Oct 29 '13 at 14:44
  • possible duplicate of [item frequency count in python](http://stackoverflow.com/questions/893417/item-frequency-count-in-python) – Maxime Chéramy Oct 29 '13 at 14:47
  • @JamesDonnelly -- you have it right, `for letter in sentence:` is the correct way to loop through each character (though using the Counter class as mentioned below is the direct solution for what you're trying to do) – Michael0x2a Oct 29 '13 at 14:49
  • 1
    http://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item-in-python – Maxime Chéramy Oct 29 '13 at 14:51
  • 1
    Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. – Marcin Oct 29 '13 at 15:01

2 Answers2

5

You can use the Counter class from collections (Python 2.7+):

>>> import collections
>>> sentence = "asdadasdsd"
>>> collections.Counter(sentence)
Counter({'d': 4, 'a': 3, 's': 3})

You can get the counts as follows:

>>> counts = collections.Counter(sentence)
>>> counts['d']
4
Simeon Visser
  • 106,727
  • 18
  • 159
  • 164
2

Well, the other solution tells you a clean way to do the job in two lines. I however am going to answer your real question on how to loop through a sentence.

Truth is, you are right. That is exactly how you loop through a sentence. See a demonstration below:

>>> sentence = "This is a sentence!"
>>> for letter in sentence:
...     print letter
...
T
h
i
s

i
s

a

s
e
n
t
e
n
c
e
!
>>>