6

次のコードがあります。これは、正規表現の置換を行うことにより、ファイルtest.texの各行を変更します。

import re
import fileinput

regex=re.compile(r'^([^&]*)(&)([^&]*)(&)([^&]*)')

for line in fileinput.input('test.tex',inplace=1):
    print regex.sub(r'\3\2\1\4\5',line),

唯一の問題は、ファイル内の特定の行にのみ置換を適用したいということです。正しい行を選択するためのパターンを定義する方法がありません。そこで、各行を表示し、コマンドラインでユーザーにプロンプ​​トを表示して、現在の行で置換を行うかどうかを尋ねます。ユーザーが「y」を入力すると、置換が行われます。ユーザーが単に何も入力しない場合、置換は行われません

もちろん、問題は、コードinplace=1を使用することで、stdoutを開いたファイルに効果的にリダイレクトしたことです。したがって、ファイルに送信されないコマンドラインに出力を表示する(たとえば、置換を行うかどうかを尋ねる)方法はありません。

何か案は?

4

2 に答える 2

4

ファイル入力モジュールは、実際には複数の入力ファイルを処理するためのものです。代わりに、通常のopen()関数を使用できます。

このようなものが機能するはずです。

ファイルを読み取り、seek()でポインターをリセットすることで、末尾に追加する代わりにファイルをオーバーライドできるため、ファイルをインプレースで編集します

import re

regex = re.compile(r'^([^&]*)(&)([^&]*)(&)([^&]*)')

with open('test.tex', 'r+') as f:
    old = f.readlines() # Pull the file contents to a list
    f.seek(0) # Jump to start, so we overwrite instead of appending
    for line in old:
        s = raw_input(line)
        if s == 'y':
            f.write(regex.sub(r'\3\2\1\4\5',line))
        else:
            f.write(line)

http://docs.python.org/tutorial/inputoutput.html

于 2012-05-30T15:22:21.027 に答える
0

みんなが提供した助けに基づいて、これが私がやったことです:

#!/usr/bin/python

import re
import sys
import os

# regular expression
regex = re.compile(r'^([^&]*)(&)([^&]*)(&)([^&]*)')

# name of input and output files
if len(sys.argv)==1:
    print 'No file specified. Exiting.'
    sys.exit()
ifilename = sys.argv[1]
ofilename = ifilename+'.MODIFIED'

# read input file
ifile = open(ifilename)
lines = ifile.readlines()

ofile = open(ofilename,'w')

# prompt to make substitutions wherever a regex match occurs
for line in lines:
    match = regex.search(line)    
    if match is not None:
        print ''
        print '***CANDIDATE FOR SUBSTITUTION***'
        print '--:  '+line,
        print '++:  '+regex.sub(r'\3\2\1\4\5',line),
        print '********************************'
        input = raw_input('Make subsitution (enter y for yes)? ')
        if input == 'y':
            ofile.write(regex.sub(r'\3\2\1\4\5',line))
        else:
            ofile.write(line)
    else:
        ofile.write(line)

# replace original file with modified file
os.remove(ifilename)
os.rename(ofilename, ifilename)

どうもありがとう!

于 2012-05-30T16:15:13.073 に答える