代码之家  ›  专栏  ›  技术社区  ›  bnbfreak

从x.dat解析到x.csv时将字符串更改为特定整数?

  •  -2
  • bnbfreak  · 技术社区  · 6 年前

    我在x.dat中有如下数据:

    1::F::1::10::48067
    2::M::56::16::70072
    3::M::25::15::55117
    

    我想转换为x.csv,将M转换为1,F转换为2,因此csv中的新结果是:

    1,2,1,10,48067
    2,1,56,16,70072
    3,1,25,15,55117
    

    在Python中如何做到这一点?

    2 回复  |  直到 6 年前
        1
  •  2
  •   Alvin    6 年前

    使用 replace

    with open("x.csv", "w") as fw:
        with open("x.dat", "r") as fr:
            for line in fr:
                new_line = line.replace("::", ",").replace("F", "2").replace("M", "1")
                fw.write(new_line)
    

    使用 re

    import re
    
    rep = {
        "F": "2",
        "M": "1",
        "::": ",",
    }
    rep = dict((re.escape(k), v) for k, v in rep.iteritems())
    pattern = re.compile("|".join(rep.keys()))
    with open("x.csv", "w") as fw:
        with open("x.dat", "r") as fr:
            for line in fr:
                new_line = pattern.sub(lambda m: rep[re.escape(m.group(0))], line)
                fw.write(new_line)
    
        2
  •  1
  •   Sumanth Rao    6 年前

    这应该起作用:

    with open("x.dat") as f:
        with open("x.csv", "w") as f1:
            for line in f:
                m= line.split("::")
                if(m[1]=='M'):
                    m[1]=1
                else:
                    m[1]=2
                for ele in m:
                    f1.write(str(ele)+',')