Reading A File Into A Dictionary And Keeping Count
I have a text file with 4 different articles containing words in it, each article is separated by the text '': Take a look at what I found.
Solution 1:
This question sounds like homework to me. So I will give you an algorithm and let you implement it yourself:
- Create an empty dictionary
- Maintain an integer (lets call it
articleNum
). Start it at 0. - Iterate through the input file (open it for reading first, preferably using
with
) - If the line you see contains
<NEW ARTICLE>
, then incrementarticleNum
. - Else, iterate through the words in the line (use
line.split()
) - For each word in the line, check if that word is a key in the dictionary
- If it is not already a key in the dictionary, add it as a key to the dictionary and make it's value a list, that contains the value of
articleNum
- If it is already a key in the dictionary, then append
articleNum
to the value of this key - Once you are done reading the file, as the user for input.
- Get the value of the user's input from the dictionary (if the input is already a key in the dictionary); this should be a list of integers
- Print out this list of integers to the user, as output
Hope this helps
Post a Comment for "Reading A File Into A Dictionary And Keeping Count"