[Tutor] count words

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Feb 15 17:59:17 CET 2005



On Tue, 15 Feb 2005, Ron Nixon wrote:

> I know that you can do this to get a count of home many times a word
> appears in a file
>
>
> f = open('text.txt').read()
> print f.count('word')
>
> Other than using a several print statments to look for seperate words
> like this, is there a way to do it so that I get a individual count of
> each word:


Hi Ron,

Let's modify the problem a bit.  Let's say that we have a list of words:

###
words = """one ring to rule them all one ring to find them
           one ring to bring them all and in the darkness bind them
           in the land of mordor where the shadows lie""".split()
###


What happens if we sort() this list?

###
>>> words.sort()
>>> words
['all', 'all', 'and', 'bind', 'bring', 'darkness', 'find', 'in', 'in',
'land', 'lie', 'mordor', 'of', 'one', 'one', 'one', 'ring', 'ring',
'ring', 'rule', 'shadows', 'the', 'the', 'the', 'them', 'them', 'them',
'them', 'to', 'to', 'to', 'where']
###


Would this be easier to process?



If you have more questions, please feel free to ask!



More information about the Tutor mailing list