用Python更新文本文件的正则表达式

时间:2015-08-25 00:13:10

标签: regex python-3.x text

我正在尝试编写一个脚本来更新文本文件,方法是用一个单词(即'a','w')替换某些字符的实例(即'a','w')。

如果单行文字是这样的:

a.function(); a.CallMethod(w); E.aa(w);

我希望它成为这个:

airplane.function(); airplane.CallMethod(worm); E.aa(worm);

差异很微妙但很重要,我只是改变'a'和'w',它用作变量,而不仅仅是另一个字中的另一个字符。文件中有很多这样的行。这是我到目前为止所做的:

original = open('original.js', 'r')
modified = open('modified.js', 'w')
# iterate through each line of the file
for line in original:
    # Search for the character 'a' when not part of a word of some sort
    line = re.sub(r'\W(a)\W', 'airplane', line)
    modified.write(line)

original.close()
modified.close()

我认为我的RE模式是错误的,我认为我也正在使用re.sub()方法。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

line = re.sub(r'\ba\b', 'airplane', line)

应该让你更接近。但请注意,您还将a.CallMethod("That is a house")替换为airplane("That is airplane house"),将open("file.txt", "a")替换为open("file.txt", "airplane")。使用RegExp在复杂的语法环境中正确使用它是很难的。