簡體   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?

所以我有兩個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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM