2012-01-22 8 views
3

私は、指定された単語で始まる行があるかどうかを調べるコードを持っています。ただし、行がスペースでインデントされていると、一部の行では機能しません。テキストを直接読み込み、スペースを無視する方法はありますか?ここで テキストの前にスペースがあるテキストを検索して置き換える方法は?

はコードです:

import os 

def template(filein): 
    currdir = os.getcwd() # get current directory 
    new_file = open(os.path.join(currdir,'maindir','template.in'),'wt') 
    old_file = open(filein) 
    for line in old_file: 
     if line.startswith(' indent'): 
      # this part works well because I put the exact number of spaces present in the text before the search word 
      new_file.write(' indent == %s \n' % str('%(indent)s')) 
     elif line.startswith('noindent'): 
      # this part can't find noindent because i didn't specify the spaces before that that is present in the text 
      new_file.write('noindent == %s \n' % str('%(noindent)s')) 
     else: 
      new_file.write(line) 
    new_file.close() 
    old_file.close() 

おかげで(問題がどこにあるかに関するコメント付き)

編集:私は、偶数ラインでは、元のファイルに存在するすべてのスペースを残しておきたいこと私は修正した。

答えて

4

あなたは、行の先頭(左)から空白を削除するlstripを使用することができます。

for line in old_file: 
    stripped_line = line.lstrip() 
    # do your matching here against `stripped_line` instead of `line` 
    # `line` still contains the original, non-stripped line 

を追記では、私が代わりにあなたが今やっていることの、with open('filename') as new_fileを使用することをお勧めします。これにより、ファイルが使用可能なブロックが作成され、ブロックの最後にファイルが閉じられることが確認されます。ドキュメントの末尾のthis sectionを参照してください。

+0

私はこれを試してみましたが、それは私が変更したくない行のために左のすべてのスペースを削除します。私はまた、私は行を変更した後、元のスペースを維持したい。ありがとう – mikeP

+1

@mikeP:行を置き換える代わりに、他の変数に格納してそれをチェックすることができます。私は答えを編集します。 –

+0

私は変更を試みましたが、私が変更した行のインデントはまだ消えています。変更した行でも元のインデントを保持したい。ありがとう。 – mikeP

0

これを行うには、lstripを使用します。

2

私はあなたがregular expressionを探していると思う:

import re 

def replace(line, test_word, new_line): 
    m = re.match(r'(\s*)(.*)', line) 
    if m.group(2).startswith(test_word) 
     return m.group(1) + new_line 

例:

>>> lines = [' my indented line', 'my not indented line'] 
>>> for line in lines: 
...  replace(line, 'my', 'new line') 
' new line' 
'new line' 

あなたはどのようgroup作品に公式ドキュメントsome examplesで見つけることができます。代わりに、文字列マッチングのマッチング

+0

ありがとうございます。書き込まれたファイルは、元のインデントを削除します。私は@ Rob Woutersの解決策を見つけました。 – mikeP

+0

@mikeP: 'm.group(1)'にはあなたのインデントがすべて含まれているので、なぜ動作しないのか分かりません。 –

0

使用する正規表現:

if re.match('^\s*indent\b', line): 
    # line starts with 0 or more whitespace followed by "indent" 
関連する問題