0

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()
4

1 に答える 1

3

これはあなたが探しているものですか?

残念ながら、どの正規表現が適用されるかを知る方法を指定しなかったので、それらをタプルのリストに入れました (最初の要素は正規表現で、2 番目は置換テキストです)。

import os, os.path, re

path = "/Users/mypath/testData"
myfiles = os.listdir(path)
# its much faster if you compile your regexes before you
# actually use them in a loop
REGEXES = [(re.compile(r'dog'), 'cat'),
           (re.compile(r'123'), '789')]
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

    # As l4mpi said ... if odt is zipped, you'd need to unzip it first
    # re.search is slower than a simple if statement
    if file_extension in ('.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:
                for search, replace in REGEXES:
                    line = search.sub(replace, line)
                fo.write(line)
        # both the input and output files are closed automatically
        # after the with statement closes
于 2012-09-23T11:15:01.453 に答える