亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在循環內迭代變量名

在循環內迭代變量名

森林海 2021-08-05 15:05:31
我幾乎沒有編程的實踐經驗,但我已經開始學習 python 并想創建一個函數來計算文本中最常用的單詞?,F在,我確信我的版本不是最好的方法,但它有效: import os punctuation = "~!@#$%^&*()_-=+[{]}\\|'\";:,<.>/?" def remove_punctuation(text):     text_wo_punctuation = ""     for word in text:         if word not in punctuation:             text_wo_punctuation += word     return text_wo_punctuation with open(r'New Text Document.txt') as f:     text = f.read().lower()     t = remove_punctuation(text).split()     dictionary = {}     for word in t:         if word in dictionary:             dictionary[word] = dictionary[word] + 1         else:             dictionary[word] = 1 print(dictionary) def top_five(d):     top = {}     value1 = 0     value2 = 0     value3 = 0     value4 = 0     value5 = 0     for key in dictionary:         if value1 < dictionary[key] and key not in top:             value1 = dictionary[key]             top1 = {key:value1}         else:             continue     top.update(top1)         for key in dictionary:         if value2 < dictionary[key] and key not in top:             value2 = dictionary[key]             top2 = {key:value2}         else:             continue     top.update(top2)     for key in dictionary:         if value3 < dictionary[key] and key not in top:             value3 = dictionary[key]             top3 = {key:value3}         else:             continue     top.update(top3)     for key in dictionary:         if value4 < dictionary[key] and key not in top:             value4 = dictionary[key]             top4 = {key:value4}         else:             continue     top.update(top4)     for key in dictionary:這段代碼將創建一個包含 value1、value2 等的字典,我可以在我的循環中使用它以及另一個包含 top1、top2 等的字典,但它不起作用,因為“并且鍵不在頂部”將不起作用。top["top"+str(i)] = {key:values["value"+str(i)]}這將在字典中創建一個字典。我被困在這里,因為我找不到使“頂級”字典有用的方法,或者在循環中迭代變量名。我讀過應該使用列表或字典,并且變量名迭代不是一個好主意,但我不明白為什么會這樣,我想不出一種方法來使列表或字典在我的 for 循環中有用。正如我所說,我知道這可能不是制作這種功能的最佳方法,但我的問題是:如何簡化我已經制作的功能并使循環正常工作?
查看完整描述

2 回答

  • 2 回答
  • 0 關注
  • 253 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號