2017-01-04 88 views
0

我試圖編寫python代碼來執行以下操作,並且卡住了。請幫忙。如何替換特定行中以「關鍵字」開頭的特定字python

我有這個文件「names.txt中」

 
rainbow like to play football 

however rainbow ... etc 

names = rainbow, john, alex 

rainbow sdlsdmclscmlsmcldsc. 

我需要在開頭線來代替彩虹字(刪除)「NAME =」

我需要的代碼搜索關鍵字「name =」 並在同一行中將單詞「rainbow」替換爲「(Removed)」,而不更改其他行中的彩虹字樣,然後覆蓋文件「names.txt」並將其更改爲:

 
rainbow like to play football 

however rainbow ... etc 

names = (Removed), john, alex 

rainbow sdlsdmclscmlsmcldsc. 

感謝

+0

向我們展示了代碼,並且您在檢查'name ='或'names =' – depperm

+1

歡迎來到Stack Overflow!您可以先參加[tour](http://stackoverflow.com/tour)並學習[如何提出一個好問題](http://stackoverflow.com/help/how-to-ask)並創建一個[最小,完整和可驗證](http://stackoverflow.com/help/mcve)示例。我們會更容易幫助你。並請檢查你的語法。 – MrLeeh

回答

0

避免正則表達式,在這裏是做

with open("names.txt") as f: 
    content = f.readlines() 

這在How do I read a file line-by-line into a list?規定和使用谷歌搜索「的文件中的巨蟒閱讀棧溢出最好的方式」被發現的一種方式。然後採取這些內容,並執行以下操作。

new_list_full_of_lines = [] # This is what you are going to store your corrected list with 
for linea in content: # This is looping through every line 
    if "names =" in linea: 
    linea.replace ("rainbow", "(Removed)") # This corrects the line if it needs to be corrected - i.e. if the line contanes "names =" at any point 
    new_list_full_of_lines.append(linea) # This saves the line to the new list 
with open('names.txt', 'w') as f: # This will write over the file 
    for item in new_list_full_of_lines: # This will loop through each line 
    f.write("%s\n" % item) # This will ensure that there is a line space between each line. 

參考 - String replace doesn't appear to be working

其他參考 - Writing a list to a file with Python

1

這將在兩個Python 2.7版(你作爲一個標籤)和Python 3

import fileinput 
import sys 

for line in fileinput.input("names.txt", inplace=1): 
    if "names = " in line: 
     line = line.replace("rainbow", "(Removed)") 
    sys.stdout.write(line) 

看做工「可選就地過濾「here(Python 2.7.13)或here(Python 3.6)。

+0

'if'條件弱。 –

+0

這是要求提出的問題。沒有進一步的澄清,這是最好的可以做到的。 –

相關問題