繁体   English   中英

RuntimeError:词典在迭代过程中更改了大小

[英]RuntimeError: dictionary changed size during iteration

这是我的代码:

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:字典在迭代过程中更改了大小”。 我的目录中只有文本文件。 任何帮助将不胜感激。

看一下这两个代码片段:

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它仍然字典保持链接 ,因此删除字典中的元素也会其从列表中删除

两种行为都可能会有所帮助,但是在您的情况下,这是您想要的第一个行为。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM