[英]Python - How can I compare a string to a dictionary of words with starting values of 0, and then increase their values by their occurrence?
So I have two txt files. 所以我有两个txt文件。 one with a list of 2000 words and another with 1000 sentences.
一个带有2000个单词的列表,另一个带有1000个句子的列表。 I also have a function that turns the list of words into a dictionary, with each word having a value of 0
我还有一个将单词列表变成字典的函数,每个单词的值为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()
Why not iterate over the words in each line? 为什么不遍历每一行中的单词呢? Suppose your dictionary is called
words_dict
. 假设您的字典称为
words_dict
。
Then: 然后:
for line in file:
for word in line:
if word in words_dict:
words_dict[word] += 1
file.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.