[英]I have a dictionary {string and int}. How do I compare integers values and not the keys within the same dictionary(python)
[英]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?
所以我有两个txt文件。 一个带有2000个单词的列表,另一个带有1000个句子的列表。 我还有一个将单词列表变成字典的函数,每个单词的值为0
因此,如果单词列表是:桔子香蕉苹果
该函数返回:
{'oranges':0, 'bananas':0, 'apples':0}
我需要将每个句子与此字典进行比较,并根据每个句子的出现频率来增加每个单词的值。
因此,如果句子是“我喜欢苹果,橙子和香蕉,但橙子是最好的。”,那么字典中应包含:
{'oranges':2, 'bananas':1, 'apples':1}
从我使用的文件访问句子
file = open(sentences.txt)
lines = file.readlines()
为什么不遍历每一行中的单词呢? 假设您的字典称为words_dict
。
然后:
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.