0

私は bash スクリプトを完全に python に移植しようとしています。これは、python に飛び込む試みとして行っています。

bash スクリプトの一部は、正規表現に応じてセクションのキャプチャを処理します。

これは私がbashスクリプトで行った方法です:

正規表現を検索します [複数行] 例: m/^[^\S\n]*\([\w0-9,*\s]*\)\s*\{[^\S\n]*\}/gm//実際の正規表現ではありません!

上記の正規表現の開始行番号を取得します

awkwhile ループで行番号から読み取りを開始するために使用します。各行をスキャンしてメソッド start を検索します。つまり、見つかった[場合は count 変数をインクリメントします。[それ以外の場合は]、カウンターをデクリメントしNRます。これにより、セクションの終了行番号がわかりました。

繰り返しますが、私awkはセクションを鳴らしていました。 nawk -v start=$var -v end=$var2 'NR >=start && NR <=end' file.sci

扱うファイル例:

!!--Blah
!!
!!
method1 {fn->23}[          --line 12
     if [ ] ;else[]
 ]                         --line 14
method2 {fn->23,f2->65}[
     if [ ] ;else[i=0]
[[[[]]]] 
 ]

bashcript が行ったことは、12 行目で method1 を開始し、この開始を awk 関数に与えて、行ごとに読み取り、カウンターをオンに[]、最後にメソッド 1 の 14 行目を与えたことです。番号 メソッドを別のファイルに取り除きました。

私は正規表現の部分を実行しましたが、行番号を使用したアプローチがPythonで実行可能かどうかはわかりません。言及されたものよりも優れたアルゴリズムが存在すると確信しています。誰かが私を正しい方向に導くか、サンプルコードまたはポインターを提供していただければ幸いです。

4

1 に答える 1

1

これは私がPythonでそれを行う方法です:

import re # to be able to use regular expressions
count = 0
found_one_at_least = False
result = ""
with open("read_file", "r") as f:
    for line in f:
        if re.search(regexp, line) is not None: # single line re to know when to start recording; returns None if there is no match, help(re.search) will tell you
            break # stop this loop and go on to the actual recording
    for line in f: # this will continue reading from where the last loop stopped, because it is an f is an iterator
        # to make it not do that you can use f.seek(0), but we do not need that
        result += line # append the line to the result
        count += line.count("[")-line.count("]") # compute the number of open/close brackets
        if count >= 1: # this is just so it does not stop at the first line if there is no [ in it
            found_one_at_least = True
        if count == 0 and found_one_at_least:
            break # stop recording when we are back at the "root" level
with open("write_file", "w") as f: # open the file, and let python handle closing and cleaning up...
    f.write(result) # write the result

サンプルのどの行とも一致しないように見えるため、正規表現のポイントは実際にはわかりませんでしたが、とにかく、好きな正規表現を使用できますが、行ベースで作業していることを忘れないでください。単一行のみ。

また、同じ正規表現を使用するので、次のようにすることをお勧めします。

regexp = re.compile(regexp_string)
# ...
if regexp.search(string) is not None:
# ...

パフォーマンスが少し向上する可能性があります。

于 2012-10-15T16:59:04.027 に答える