簡體   English   中英

計算文本中每個單詞的出現次數

[英]count the number of occurences of each word in the text

我正在嘗試計算文本中每個單詞的出現次數,我有下面的代碼,但它似乎沒有跳轉到循環的 else 部分如果代碼不清楚,我已經添加了它的圖像

enter code here text = “快樂就是快樂,但快樂不是找到解決方案” enter code here x= {}

在 text.lower().split() 中為 mot enter code here enter code here :如果 x.get(mot) 不在 x.keys() 中,則在enter code here print(mot) enter code here x[mot] = 1 enter code here print(x[mot]) enter code here else: 在此處enter code here print("單詞是" + mot) enter code here x[mot] = (x[mot]+1) print((x[mot ])) 打印(x)

X

任何幫助都可以通過 if 循環解決它

在此處輸入圖像描述

您正在檢查 if 語句中的錯誤條件,當您調用 get 方法並將其傳遞給它返回其值的鍵時,這意味着您正在檢查該字典鍵中該鍵的值。 它的工作解決方案可能是:

text = "Joy is joy but joy is not finding a solution" 
x= {}
for mot in text.lower().split(): 
    if mot not in x.keys(): 
        x[mot] = 1 
    else:
        x[mot] += 1

print(x)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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