0
改變大小這是我的代碼:「:迭代過程中改變字典大小RuntimeError」在編寫這些代碼RuntimeError:字典中迭代
import os
import collections
def make_dictionary(train_dir):
emails=[os.path.join(train_dir,f) for f in os.listdir(train_dir)]
all_words=[]
for mail in emails:
with open(mail) as m:
for i,line in enumerate(m):
if i==2: #Body of email is only 3rd line of text file
words=line.split()
all_words+=words
dictionary=collections.Counter(all_words)
# Paste code for non-word removal here(code snippet is given below)
list_to_remove=dictionary.keys()
for item in list_to_remove:
if item.isalpha()==False:
del dictionary[item]
elif len(item)==1:
del dictionary[item]
dictionary=dictionary.mostcommon[3000]
print (dictionary)
make_dictionary('G:\Engineering\Projects\Python\Documents\enron1\ham')
我收到錯誤。我只有 目錄中的文本文件。任何幫助將不勝感激。
將'list_to_remove = dictionary.keys()'改爲'list_to_remove = [k for dictionary in dictionary]''以避免*將'keys'的'list'關聯到'dict',字典'不反映回'列表' –
謝謝。有用。 @ Ev.Kounis –