简体   繁体   English

如何从“关键字” python开始替换特定行中的特定单词

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

I've tried to write python code to do the following, and I'm stuck. 我试图编写python代码来执行以下操作,但遇到了麻烦。 Please help. 请帮忙。

I have this file "names.txt" 我有这个文件“ names.txt”

rainbow like to play football

however rainbow ... etc

names = rainbow, john, alex 

rainbow sdlsdmclscmlsmcldsc.

I need to replace rainbow word to (Removed) in line which starts with "name = " 我需要将彩虹字替换为(已删除)以“ name =”开头的行

I need the code to search for keyword " name = " and replace the word "rainbow" to " (Removed") in the same line without changing the words rainbow in other lines, then overwrite the file "names.txt" with the changes to be like: 我需要代码来搜索关键字“ name =”,并在同一行中将单词“ rainbow”替换为“(已删除)”,而无需更改其他行中的Rainbow单词,然后用所做的更改覆盖文件“ names.txt”像是:

rainbow like to play football

however rainbow ... etc

names = (Removed), john, alex 

rainbow sdlsdmclscmlsmcldsc.

Thanks 谢谢

This will work in both Python 2.7 (which you used as a tag) and Python 3. 这将在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)

See "Optional in-place filtering" here (Python 2.7.13) or here (Python 3.6). 请参阅此处 (Python 2.7.13)或此处 (Python 3.6)的“可选的就地过滤”。

Avoiding regex, here is one way of doing it 避免正则表达式,这是一种实现方式

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

This was stated in How do I read a file line-by-line into a list? 我如何将文件逐行读入列表中进行了说明? and was found using google searching "stack overflow best way of reading in a file python". 并且被发现使用谷歌搜索“在文件python中读取堆栈溢出的最佳方式”。 Then take this content, and do the following. 然后获取此内容,然后执行以下操作。

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.

Reference - String replace doesn't appear to be working 参考- 字符串替换似乎不起作用

Other reference - Writing a list to a file with Python 其他参考- 使用Python将列表写入文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM