簡體   English   中英

如何從“關鍵字” python開始替換特定行中的特定單詞

[英]How to replace a specific word in specific line starting with a “keyword” python

我試圖編寫python代碼來執行以下操作,但遇到了麻煩。 請幫忙。

我有這個文件“ names.txt”

rainbow like to play football

however rainbow ... etc

names = rainbow, john, alex 

rainbow sdlsdmclscmlsmcldsc.

我需要將彩虹字替換為(已刪除)以“ name =”開頭的行

我需要代碼來搜索關鍵字“ name =”,並在同一行中將單詞“ rainbow”替換為“(已刪除)”,而無需更改其他行中的Rainbow單詞,然后用所做的更改覆蓋文件“ names.txt”像是:

rainbow like to play football

however rainbow ... etc

names = (Removed), john, alex 

rainbow sdlsdmclscmlsmcldsc.

謝謝

這將在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)

請參閱此處 (Python 2.7.13)或此處 (Python 3.6)的“可選的就地過濾”。

避免正則表達式,這是一種實現方式

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

我如何將文件逐行讀入列表中進行了說明? 並且被發現使用谷歌搜索“在文件python中讀取堆棧溢出的最佳方式”。 然后獲取此內容,然后執行以下操作。

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.

參考- 字符串替換似乎不起作用

其他參考- 使用Python將列表寫入文件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM