ファイルから正規表現を取得し、別のファイルで検索と置換を実行する簡単なスクリプトを作成しようとしています。これは私が持っているものですが、機能しません。ファイルは変更されていません。何が間違っているのでしょうか。
import re, fileinput
separator = ' => '
file = open("searches.txt", "r")
for search in file:
pattern, replacement = search.split(separator)
pattern = 'r"""' + pattern + '"""'
replacement = 'r"""' + replacement + '"""'
for line in fileinput.input("test.txt", inplace=1):
line = re.sub(pattern, replacement, line)
print(line, end="")
ファイルsearches.txtは次のようになります。
<p (class="test">.+?)</p> => <h1 \1</h1>
(<p class="not">).+?(</p>) => \1This was changed by the script\2
そしてこのようなtest.txt:
<p class="test">This is an element with the test class</p>
<p class="not">This is an element without the test class</p>
<p class="test">This is another element with the test class</p>
ファイルから式が正しく取得されているかどうかを確認するためのテストを行いました。
>>> separator = ' => '
>>> file = open("searches.txt", "r")
>>> for search in file:
... pattern, replacement = search.split(separator)
... pattern = 'r"""' + pattern + '"""'
... replacement = 'r"""' + replacement + '"""'
... print(pattern)
... print(replacement)
...
r"""<p (class="test">.+?)</p>"""
r"""<h1 \1</h1>
"""
r"""(<p class="not">).+?(</p>)"""
r"""\1This was changed by the script\2"""
最初の置換の最後のトリプルクォートは、何らかの理由で改行になっていますが、これが私の問題の原因である可能性がありますか?