2017-06-04 507 views
0

我有對數字的文件如下:如何在python中只替換文本中的一個數字?

0,21 
0,52 
0,464 
100,478 
1,101 
1,729 
1,730 

而且我想用「2000」來取代單「0」。預期結果應該是:

2000,21 
2000,52 
2000,464 
100,478 
1,101 
1,729 
1,730 

然而,我的代碼,它改變了全0至2000年,我結束了這樣的輸出:

2000,21 
2000,52 
2000,464 
120002000,478 
1,120001 
1,729 
1,732000 

我的代碼是:

textToSearch = "0" 
textToReplace = "2000" 
fileToSearch = "example.csv" 
with fileinput.FileInput(fileToSearch, inplace=True, backup='.bak') as file: 
    for line in file: 
     print(line.replace(textToSearch, textToReplace), end='') 

加號:我永遠不會知道逗號左側有多少個0,因此我無法限制要更改的0的數量。該文件是隨機生成的,因爲有時我有十二個零,有時只有一個。 我已經試過這樣:

textToSearch = "0," 
textToReplace = "2000," 
fileToSearch = "example.csv" 
with fileinput.FileInput(fileToSearch, inplace=True, backup='.bak') as file: 
    for line in file: 
     print(line.replace(textToSearch, textToReplace), end='') 

然而,這一次卻是不工作的號碼如"100""200",因爲它是分別讓他們"102000""202000"

我該如何解決?

回答

1

這稍作修改以將您的數據保存到文件。基本算法沒有改變。

import re 

temp = [] 

with open("example.csv", "r") as inputf: 
    for line in inputf: 
     line = line.strip("\n") 
     match = re.search("^0", line) 
     if match: 
      list1 = line.split(",") 
      list1[0] = 2000 
      line = str(list1[0]) + "," + str(list1[1]) 
     temp.append(line) 
inputf.close() 

# overwrite original file 

with open("example.csv", "w") as outputf: 
    for item in temp: 
     outputf.write(item + "\n") 
outputf.close() 
0

您應該嘗試使用「正則表達式」import re模塊,如下所示。

import re  

fileToSearch = "example.csv" 

    with open(fileToSearch) as file: 
     for line in file: 
      line = line.strip("\n") 
      match = re.search("^0", line) 
      if match: 
       list1 = line.split(",") 
       list1[0] = 2000 
       line = str(list1[0]) + "," + str(list1[1]) 
      print(line) 

這似乎產生你想要的結果。

+0

謝謝!我無法將輸出(行)寫入文件。我已經將open(fileToSearch,'w')作爲文件進行了更改,並在最後添加了file.write(line)。但是,沒有工作。你也許知道爲什麼? – bapors

0

KISS方法。在使用正則表達式時,我想出了一個更短,更簡單的解決方案,您可能會考慮使用它。

import re   

with open("example.csv", "r") as inputf: 

    randstr = inputf.read() 
    regex = re.compile(r"\b0\b") 
    result = re.sub(regex, "2000", randstr) 

with open("example.csv", "w") as outputf: 
    outputf.write(result)