繁体   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