RuntimeError:字典在迭代期间改变了大小

时间:2017-07-12 16:00:00

标签: python runtime-error

这是我的代码:

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')

我在编写此代码时收到错误“RuntimeError:字典在迭代期间更改了大小”。我有 只有目录中的文本文件。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分: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彼此无关; dict中的更改不会反映到列表中。

在第二个代码段上,由于我们创建列表f的方式,它仍然链接到dict,因此删除dict的元素也删除它们从列表中。

这两种行为可能会有所帮助,但在您的场景中,它是您想要的第一个行为。