在.csv中用其他值替换特定值,“tuple”对象没有属性?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (142)

我可以找到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,另一方为1。

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

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)

扫码关注云+社区

领取腾讯云代金券