【问题标题】:Why is this replace method not working properly为什么此替换方法无法正常工作
【发布时间】:2019-10-01 02:26:35
【问题描述】:

我有一个文件,其中的数据如下所示:

1 1:-0.03125 2:0.236364 3:0.142857 4:-0.107438 5:0.129032 6:0.163636 7:0.242105
2 1:-0.03125 2:0.472727 3:0.761905 4:0.123967 6:0.472727 7:0.347368
....

总共有几千行。我正在尝试将其转换为 csv 文件。

我尝试了以下代码:

with open("file1.test", "r") as infile:
    with open("file1.csv", "w") as outfile:
        for line in infile:
            new_line = line
            i = 1
            for i in range(1,8):
                to_replace = " " + str(i) + ":"
                new_line = new_line.replace(to_replace, ",", 1)
            new_line = line[:2] + "," + line[2:]
            new_line = new_line.replace(" ", "", 1)


但它没有按预期工作。 new_line = new_line.replace(" ", "", 1) 行有效,但是当我尝试用逗号替换“1:”时,它不会更新。我希望我的最终文件看起来像“

1, -0.03125,0.236364,0.142857,-0.107438,0.129032,0.163636,0.242105
2,-0.03125,0.472727,0.761905,0.123967,0.472727,0.347368 

任何想法我做错了什么?

【问题讨论】:

  • 您的.replace()s 可能一切正常。但是,您放弃了使用声明 new_line = line[:2] + "," + line[2:] 的所有工作,它仅使用 line 的原始值。

标签: python string replace


【解决方案1】:

您可以对每一行尝试这种转换方法:

>>> a = '1 1:-0.03125 2:0.236364 3:0.142857 4:-0.107438 5:0.129032 6:0.163636 7:0.242105'
>>> ','.join( [i.split(':')[-1] for i in a.split()] )
'1,-0.03125,0.236364,0.142857,-0.107438,0.129032,0.163636,0.242105'

你的整个程序看起来像这样:

with open("file1.test", "r") as infile:
    text = [i.strip() for i in infile.readlines()]

output = []
for t in text :
    output.append( ','.join( [i.split(':')[-1] for i in t.split()] ) )

with open("file1.csv", "w") as outfile:
    outfile.write( '\n'.join( output ) )

【讨论】:

    【解决方案2】:

    我喜欢这个

    import re  
    with open("file1.test", "r") as infile:
        with open("file1.csv", "w") as outfile:
            for line in infile:
                outfile.write(re.sub(' [1-7]:',',',line))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-28
      • 1970-01-01
      • 2020-03-06
      • 2011-07-24
      • 2017-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多