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

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to