我?guī)缀鯖]有編程的實踐經(jīng)驗,但我已經(jīng)開始學(xué)習(xí) python 并想創(chuàng)建一個函數(shù)來計算文本中最常用的單詞?,F(xiàn)在,我確信我的版本不是最好的方法,但它有效: 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:這段代碼將創(chuàng)建一個包含 value1、value2 等的字典,我可以在我的循環(huán)中使用它以及另一個包含 top1、top2 等的字典,但它不起作用,因為“并且鍵不在頂部”將不起作用。top["top"+str(i)] = {key:values["value"+str(i)]}這將在字典中創(chuàng)建一個字典。我被困在這里,因為我找不到使“頂級”字典有用的方法,或者在循環(huán)中迭代變量名。我讀過應(yīng)該使用列表或字典,并且變量名迭代不是一個好主意,但我不明白為什么會這樣,我想不出一種方法來使列表或字典在我的 for 循環(huán)中有用。正如我所說,我知道這可能不是制作這種功能的最佳方法,但我的問題是:如何簡化我已經(jīng)制作的功能并使循環(huán)正常工作?
添加回答
舉報
0/150
提交
取消