0

So I have two txt files. one with a list of 2000 words and another with 1000 sentences. I also have a function that turns the list of words into a dictionary, with each word having a value of 0

So if the word list was : oranges bananas apples

The function returns:

{'oranges':0, 'bananas':0, 'apples':0}

I need to compare each sentence with this dictionary and increase the values for every word based on their frequency of the sentence.

So if the sentence was "I like apples, oranges, and bananas, but oranges are the best.", then the dictionary should contain:

{'oranges':2, 'bananas':1, 'apples':1}

To access the sentences from the file I used

file = open(sentences.txt)
lines = file.readlines()
Bida B
  • 3
  • 1
  • Possible duplicate of [Count frequency of words in a list and sort by frequency](https://stackoverflow.com/questions/20510768/count-frequency-of-words-in-a-list-and-sort-by-frequency) – stovfl Nov 25 '18 at 20:57
  • Welcome to StackOverflow. This question is missing context or other details: Please improve the question by providing additional context, which ideally includes your thoughts on the problem and any attempts you have made to solve it. This information helps others identify where you have difficulties and helps them write answers appropriate to your experience level. You also need to state exactly what the problem is, what you expected, what you got, and any traceback. – Rory Daulton Nov 25 '18 at 21:17

1 Answers1

0

Why not iterate over the words in each line? Suppose your dictionary is called words_dict.

Then:

for line in file:
    for word in line:
        if word in words_dict:
           words_dict[word] += 1 

file.close()
Yakov Dan
  • 2,157
  • 15
  • 29