Reading a File into a Dictionary And Keeping Count

前端 未结 1 559
自闭症患者
自闭症患者 2021-01-28 17:12

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



        
1条回答
  •  孤城傲影
    2021-01-28 17:28

    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 , 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

    0 讨论(0)
提交回复
热议问题