[Tutor] count words
Ron Nixon
nixonron at yahoo.com
Tue Feb 15 18:19:38 CET 2005
Thanks to everyone who replied to my post. All of your
suggestions seem to work. My thanks
Ron
--- Ryan Davis <ryan at acceleration.net> wrote:
> You could use split() to split the contents of the
> file into a list of strings.
>
> ###
> >>> x = 'asdf foo bar foo'
> >>> x.split()
> ['asdf', 'foo', 'bar', 'foo']
> ###
>
> Here's one way to iterate over that to get the
> counts. I'm sure there are dozens.
> ###
> >>> x = 'asdf foo bar foo'
> >>> counts = {}
> >>> for word in x.split():
> ... counts[word] = x.count(word)
> ...
> >>> counts
> {'foo': 2, 'bar': 1, 'asdf': 1}
> ###
> The dictionary takes care of duplicates. If you are
> using a really big file, it might pay to eliminate
> duplicates from the list
> before running x.count(word)
>
> Thanks,
> Ryan
>
> -----Original Message-----
> From: tutor-bounces at python.org
> [mailto:tutor-bounces at python.org] On Behalf Of Ron
> Nixon
> Sent: Tuesday, February 15, 2005 11:22 AM
> To: tutor at python.org
> Subject: [Tutor] count words
>
>
> 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:
>
> word1 xxx
> word2 xxx
> words xxx
>
> etc.
>
>
>
>
>
> __________________________________
> Do you Yahoo!?
> Yahoo! Mail - Find what you need with new enhanced
> search.
> http://info.mail.yahoo.com/mail_250
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
__________________________________
Do you Yahoo!?
The all-new My Yahoo! - Get yours free!
http://my.yahoo.com
More information about the Tutor
mailing list