0

私はファイルを持っています。テキストが "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()

助けてください

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 に答える