0

我有一个文件。我想用哈希 (#) 评论那些有文本的行是“测试”。

一个.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()

请帮忙

4

1 回答 1

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))
于 2013-07-29T18:03:13.040 回答