Reading a File into a Dictionary And Keeping Count

2020-05-06 12:02发布

问题:

I have a text file with 4 different articles containing words in it, each article is separated by the text "<NEW ARTICLE>":

<NEW ARTICLE>
Take a look at 
what I found.
<NEW ARTICLE>
It looks like something
dark and shiny.
<NEW ARTICLE>
But how can something be dark
and shiny at the same time?
<NEW ARTICLE>
I have no idea.

What I want to do is read this file and turn it into a dictionary, and then keep count of how many times "<NEW ARTICLE>" or "ARTICLE>" is used. That way when I search for the words "dark and shiny" it goes to the 2nd and 3rd time "<NEW ARTICLE>" appears.

The word to search for will be a user inputted variable, and I think I can figure out how to search for it in the file, I'm just having trouble figuring out how to turn the contents of the file into a dictionary and then keeping count everytime "<NEW ARTICLE>" or "ARTICLE>" appears so that when a user searches for a word in the file, it displays the number of the article in which the word the exists (can be multiple instances of the word in multiple articles).

The output would look something like this:

Input - Word(s) to search for: dark and shiny
Output - Word(s) found in articles: 2 3
Input - Read which article?: 2
Output - It looks like something dark and shiny.

Using Python 3, thanks.

回答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