如何替换特定行中的特定单词,以"关键字"开头蟒蛇

时间:2017-01-04 15:54:59

标签: python python-2.7

我尝试编写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.

由于

2 个答案:

答案 0 :(得分: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)。

答案 1 :(得分:0)

避免正则表达式,这是一种方法

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

这在How do I read a file line-by-line into a list?中有所说明,并且使用谷歌搜索“堆栈溢出在文件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.

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

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