我有一个文件。我想用hash(#)注释那些文本为“test”的行。
A.TXT:
this is test
test is this
this test is good
this good
所以输出应该是......
#this is test
#test is this
#this test is good
this good
我尝试使用正则表达式但不能完美运行。
def convert_string():
import re
fh=open("tt.txt","rb")
lines=fh.readlines()
for line in lines:
line= re.sub(r'^(test)',r'#\1',line)
print line
fh.close()
请帮助
答案 0 :(得分:1)
正则表达式对此有些过分。如果要检查较大字符串中是否存在子字符串,只需使用in
:
def comment_out(infilepath, outfilepath):
with open(infilepath) as infile, open(outfilepath, 'w') as outfile:
for line in infile:
if 'test' not in line:
outfile.write(line)
else:
outfile.write("#" + line)
如果你想要单行:
def comment_out(infilepath, outfilepath):
with open(infilepath) as infile, open(outfilepath, 'w') as outfile:
for line in infile:
outfile.write(line if 'test' not in line else "#"+line)
如果要覆盖原始文件(这具有线性空间复杂性):
def comment_out(infilepath):
with open(infilepath) as infile:
lines = list(infile)
with open(infilepath, 'w') as outfile:
outfile.write(''.join(line if 'test' not in line else "#"+line for line in lines))