首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将元组中的特定值替换为其他值时,“.csv”对象没有属性

将元组中的特定值替换为其他值时,“.csv”对象没有属性
EN

Stack Overflow用户
提问于 2018-08-08 01:29:30
回答 1查看 55关注 0票数 -1

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

代码语言:javascript
复制
    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文件的示例:

代码语言:javascript
复制
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

但在我的程序中,我得到了这个错误:

代码语言:javascript
复制
     for i, j in replacements.iteritems():
     AttributeError: 'tuple' object has no attribute 'iteritems'
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-08 02:19:09

通常情况下,字典是替换甚至翻译的首选,您可以使用函数dict(replacements)将替换内容更改为字典

代码语言:javascript
复制
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)

现在,其余部分保持不变。例如,你可以添加outputfile.write(line)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51732376

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档