简体   繁体   English

Python-如何将字符串与起始值为0的单词词典进行比较,然后通过出现它们增加其值?

[英]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.

相关问题 我有一本字典 {string and int}。 如何比较整数值而不是同一字典中的键(python) - I have a dictionary {string and int}. How do I compare integers values and not the keys within the same dictionary(python) Python计算字典中值的出现 - Python counting occurrence of values in dictionary 当我使用 function eval(String dictionary) -> dictionary PYTHON 时,如何处理字典中的缺失值? - How can I handle missing values in the dictionary when I use the function eval(String dictionary) -> dictionary PYTHON? Python字典 - 比较值 - Python dictionary - compare values 字典我如何将值更改为字符串 - Dictionary how can i change values to string 如何将用户整数输入与字典中的值进行比较? (Python) - How do I compare user integer input to values in dictionary? (Python) 如何在一本字典中比较两个不同的值(数组)? - How can I compare two different values(array) in one dictionary? 在 Python 中,我将如何比较一个字典中的两个值在另一个字典中具有相同的值? - In Python how would I compare 2 values in one dictionary that have the same values in another dictionary? 如何从另一个python字典中的一个字典中获得相应的列表值,在列表中它们被列为键,比较并打印出csv? - How can I get corresponding list values in one dictionary from another python dictionary where they are listed as keys, compare and print out a csv? 如何比较字典中的值 - How to compare values in a dictionary
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM