Pythonを使用して約100個のファイルに12個ほどの正規表現を適用する必要がある1つのプロジェクトがあります。「(merge|concatenate|stack|join|compile) Python での複数の正規表現」を含むさまざまな組み合わせを Web で検索するのに 4 時間以上かかりましたが、私の必要性に関する投稿は見つかりませんでした。
これは私にとって中規模のプロジェクトです。私が必要とするいくつかの小さな正規表現プロジェクトがあり、これらはわずか 10 個ほどのファイルに適用される 5 ~ 6 個の正規表現パターンのみを使用します。これらは私の仕事に大いに役立ちますが、おじいちゃんプロジェクトは、100 以上の検索のファイルを適用し、取得した新しいファイルに文字列を置き換えます。(特定の言語のスペル規則は標準化されておらず、ファイルをすばやく処理できると生産性が向上します。)
理想的には、正規表現文字列はプログラマー以外でも更新できる必要がありますが、それはこの投稿の範囲外である可能性があります。
これが私がこれまでに持っているものです:
import os, re, sys # Is "sys" necessary?
path = "/Users/mypath/testData"
myfiles = os.listdir(path)
for f in myfiles:
# split the filename and file extension for use in renaming the output file
file_name, file_extension = os.path.splitext(f)
generated_output_file = file_name + "_regex" + file_extension
# Only process certain types of files.
if re.search("txt|doc|odt|htm|html")
# Declare input and output files, open them, and start working on each line.
input_file = os.path.join(path, f)
output_file = os.path.join(path, generated_output_file)
with open(input_file, "r") as fi, open(output_file, "w") as fo:
for line in fi:
# I realize that the examples are not regex, but they are in my real data.
# The important thing, is that each of these is a substitution.
line = re.sub(r"dog","cat" , line)
line = re.sub(r"123", "789" , line)
# Etc.
# Obviously this doesn't work, because it is only writing the last instance of line.
fo.write(line)
fo.close()