[Tutor] Counting Items in a List
Steven D'Aprano
steve at pearwood.info
Wed Jun 20 21:39:50 CEST 2012
Oğuzhan Öğreden wrote:
> Hi,
>
> 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:
[code snipped]
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:
import collections
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:
counts.most_common(5)
=> [('the', 6), ('are', 3), ('placeholders', 3), ('and', 2), ('kws', 2)]
or look up the counts of words:
counts['keys']
=> 1
counts['oranges']
=> 0
More about Counter here:
http://docs.python.org/library/collections.html#collections.Counter
--
Steven
More information about the Tutor
mailing list