为什么此替换方法无法正常工作

时间:2019-10-01 02:26:35

标签: python string replace

我有一个文件,其数据看起来像这样:

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 

有什么想法我做错了吗?

2 个答案:

答案 0 :(得分:1)

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

var n = 3;
var counter  = 1;
var outerArray = [];

// Now just add to the array with a nested for loop
for(var i = 0; i < n; i++) {
    // Add empty array to the outer array.
    outerArray.push([]);
    // outer for loop steps through the rows
    for(var j = 0; j < n; j++) {
        // The inner loop steps through the columns
        outerArray[i][j] = counter;
        counter++;
    }
  }
// Now just print the array.
console.log(outerArray);

整个程序如下:

>>> 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'

答案 1 :(得分:1)

我喜欢这个

Object has been disposed.