Python 3.x 用.csv和#x27中的其他值替换特定值;元组';对象没有属性

Python 3.x 用.csv和#x27中的其他值替换特定值;元组';对象没有属性,python-3.x,csv,Python 3.x,Csv,我可以找到hwo来调试我的代码 with open("f_in.csv",'rb') as f, open("f_out.csv", "w") as outputfile: for line in f: replacements = ( ("(B)", "0"), ("(D)", "2"), ("Entrée air absente", "2"), ("+", "0,5"), ("++", "1"), ("+++", "2"),

我可以找到hwo来调试我的代码

    with open("f_in.csv",'rb') as f, open("f_out.csv", "w") as outputfile:
        for line in f:

    replacements = (
        ("(B)", "0"), ("(D)", "2"), ("Entrée air absente", "2"),
        ("+", "0,5"), ("++", "1"), ("+++", "2"),
        ("(S) +", "0,5"), ("(S) expi. ++", "1"), ("(S) +++", "2"),
        ("100", "0"), ("99", "0"), ("98", "0"), ("97", "0"), ("96", "0"), 
        ("95", "0"), ("94", "1"),("93", "1"),
        ("92", "1"),("91", "1"),("90", "1"),("89", "1"))

    for i, j in replacements.iteritems():
         line = line.replace(i, j)
         outputfile.write(line)`

    for pair in replacements:
        line = line.replace(*pair)
我想在csv文件的每一行中用一个特定的数字替换一些值

所以(B)将是0,(D)将是2,+将是0.5,++将是1,+++将是2,所以一个代表另一个

csv文件示例:

1277|2013-12-17 16:00:00|100|+|
1360|2014-01-15 16:00:00|(B)|99|++|E
1402|2014-02-05 20:00:00|(D)|99|++|D
1360|2014-01-29 08:00:00|(D)|99||C
1378|2014-01-21 20:00:00|(B)|100||D
但在我的程序中,我得到了以下错误:

     for i, j in replacements.iteritems():
     AttributeError: 'tuple' object has no attribute 'iteritems'

通常在替换或翻译中首选词典,您可以使用函数
dict(replacements)
,将替换内容更改为词典:


现在剩下的都没变。例如,您可以添加
outputfile.write(line)
etc

您可能想做的是使用
re.sub进行一些替换
Ok我必须学习如何使用regex它似乎非常有用我现在遇到了这个错误
line=re.sub(r'\(\w\),lambda x:dict(replacements)[x.string[x.start():x.end()],i)keyrerror:'(S)“
@Zenix sorry从未想过您必须替换替换元组中的所有内容。我已编辑代码:
replacements = (
        ("(B)", "0"), ("(D)", "2"), ("Entrée air absente", "2"),
        ("+", "0,5"), ("++", "1"), ("+++", "2"),
        ("(S) +", "0,5"), ("(S) expi. ++", "1"), ("(S) +++", "2"),
        ("100", "0"), ("99", "0"), ("98", "0"), ("97", "0"), ("96", "0"), 
        ("95", "0"), ("94", "1"),("93", "1"),
        ("92", "1"),("91", "1"),("90", "1"),("89", "1"))


import re


replvalues = dict(replacements)
regex = "|".join(map(re.escape,replvalues.keys()))
repl = lambda x : replvalues.get(x.string[x.start():x.end()])
with open("f_in.csv") as f:
        for i in f:
            line =  re.sub(regex,repl, i)
            print(line)