[Tutor] creat a program that reads frequency of words in file

Alan Gauld alan.gauld at btinternet.com
Tue Jun 2 01:42:22 CEST 2015


I've CCd the list. Please use reply all when responding to the list.
Also please use plain text as HTML/RTF doesn't work on all
systems and code in particular often gets mangled.

On 01/06/15 23:59, Stephanie Quiles wrote:
> Hello again,
>
> here is the final code… I think :) please see below. Is this is the 
> easiest way to go about it? I appreciate your assistance!
>
> defmain():
>      words = {}
>      count =0

Do you need count? What is its purpose?
>      withopen('words.txt')asdata:
>          forlineindata:
>              text = line.split()
>              forwordintext:
>                  ifwordnot inwords:
>                      words[word] =1
>                  else:
>                      words[word] +=1

Look into the setdefault() method of dictionaries.
It can replace the if/else above.

>              count +=1
>      print(words)

Aside from the two comments above, good job!

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list