2017-07-12 73 views
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') 

我收到错误。我只有 目录中的文本文件。任何帮助将不胜感激。

+0

将'list_to_remove = dictionary.keys()'改为'list_to_remove = [k for dictionary in dictionary]''以避免*将'keys'的'list'关联到'dict',字典'不反映回'列表' –

+0

谢谢。有用。 @ Ev.Kounis –

回答

0

看看这两段代码:

d = {1: 1, 2: 2} 
f = [x for x in d] 
del d[1] 
print(f) # [1, 2] 

和:

d = {1: 1, 2: 2} 
f = d.keys() 
del d[1] 
print(f) # dict_keys([2]) 

正如你所看到的,在第一个字典d和列表f不相关的一个另一个;字典中的更改未反映到列表中。

在第二个片段,由于在路上,我们创建列表f它仍然链接如此删除字典元素的字典也从列表中删除他们。

这两种行为都可能是有用的,但在你的情况下,它是你想要的第一个。