[Tutor] Counting Items in a List
steve at pearwood.info
Wed Jun 20 21:39:50 CEST 2012
Oğuzhan Öğreden wrote:
> I have been learning Python and trying little bits of coding for a while.
> Recently I tried to have a paragraph and create a list of its words, then
> counting those words. Here is the code:
I can't understand your code! Indentation is messed up badly. It has
inconsistent numbers of > quote marks at the start of some lines. It's a mess.
If you are using Python 2.7 or better, the best way to count items in a list
is with a Counter object:
text = """
Performs the template substitution, returning a new string.
mapping is any dictionary-like object with keys that match the
placeholders in the template. Alternatively, you can provide keyword
arguments, where the keywords are the placeholders. When both
mapping and kws are given and there are duplicates, the placeholders
from kws take precedence.
text = text.replace('.', '').replace(',', '')
words = text.lower().split()
counts = collections.Counter(words)
Once I do this, I can check the most common words:
=> [('the', 6), ('are', 3), ('placeholders', 3), ('and', 2), ('kws', 2)]
or look up the counts of words:
More about Counter here:
More information about the Tutor