[Tutor] creat a program that reads frequency of words in file
Alan Gauld
alan.gauld at btinternet.com
Mon Jun 1 11:56:08 CEST 2015
On 01/06/15 05:01, Stephanie Quiles wrote:
> Hello. i need serious help. i am a very very new python programmer.
Welcome.
> Write a program that reads the contents of a text file.
OK, Well you have done that bit OK.
> The program should create a dictionary in which the
> keys are the individual words found in the file
But you are failing on this bit. As you said you are not storing
anything in the dictionary. You need to split your lines into individual
words, then store each word in the dictionary.
I suggest you simplify the problem for now and try just doing that.
Don't worry about counting them for now just save the words into the
dictionary. You should end up with the dictionary containing one entry
for each of the different words in the file.
Some other comments below.
> def main():
> dict = {}
Don't use dict as a variable because thats a Python function for
creating dictionaries. By using it as a name you hide the
function. AS a general rule never name variables after
their type, name them after their purpose. In this case it could be
called 'words' or 'counts' or something similar.
> count = 0
> text = input('enter word: ')
You weren't asked to read a word from the user.
All the data you need is in the file.
> data = open("words.txt").readlines()
> for line in data:
You don't need the readlines() line you can just do
for line in open("words.txt"):
However, best practice says that this is even better:
with open("words.txt") as data:
for line in data:
This ensures that the file is correctly closed
at the end.
> if text in line:
> count += 1
> print("This word appears", count, "times in the file")
And this is, of course, completely off track. You need
to split the line into its separate words and store
each word into the dictionary.
HTH
--
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