Skip to content Skip to sidebar Skip to footer

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:

  1. Create an empty dictionary
  2. Maintain an integer (lets call it articleNum). Start it at 0.
  3. Iterate through the input file (open it for reading first, preferably using with)
  4. If the line you see contains <NEW ARTICLE>, then increment articleNum.
  5. Else, iterate through the words in the line (use line.split())
  6. For each word in the line, check if that word is a key in the dictionary
  7. 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
  8. If it is already a key in the dictionary, then append articleNum to the value of this key
  9. Once you are done reading the file, as the user for input.
  10. 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
  11. 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"