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我已经有效地将标准输出重定向到打开的文件的代码。因此,没有办法向未发送到文件的命令行显示输出(例如询问是否进行替换)。

有任何想法吗?

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 回答