2017-01-04 61 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

这是要求提出的问题。没有进一步的澄清,这是最好的可以做到的。 –

相关问题