为什么我会收到属性错误?蟒蛇

时间:2018-01-26 19:31:31

标签: python replace attributeerror

所以我试图获得一个大规模的替换,我得到一个属性错误,我不明白为什么,我甚至跟着其他人的例子。 这是我的代码

def replace_all(text, dic):
    for i, j in dic.iteritems():
        text = text.replace(i, j)
    return text

def Cleaner(inf, ouf):
    A = open(inf, "w+")
    B = open(ouf, "w+")
    reps = {"Bonus":"", "January":"", "February":"", "March":"", "April":"", "May":"", "June":"", "July":"", "August":"", "September":"", "October":"", "November":"", "December":""}
    txt = replace_all(A.read(), reps)
    B.write(txt)

这是错误

line 2, in replace_all
    for i, j in dic.iteritems():
AttributeError: 'dict' object has no attribute 'iteritems'

这是我遵循的例子 This is the link used for the code above

1 个答案:

答案 0 :(得分:0)

你可能正在使用Python 3 而不是Python 2 ,在这种情况下,你需要dict.items()而不是iteritems()

def replace_all(text, dic):
    for i, j in dic.items():
        text = text.replace(i, j)
    return text

这是一个测试:

>>> replace_all("hello bob", {"hello":"goodbye", "bob": "fish"})
'goodbye fish'
相关问题