2017-01-09 14 views
0

C++ソースコードファイル内で、配列変数を関数に置き換えます。 さらに、ハードコードされた数値を列挙型に置き換える必要があります。 これに対して、私は正規表現と辞書を使うと考えました。 dictは、関連付けを列挙するための番号を表します。正規表現:テキスト変数と括弧内の数字を一致するdictエントリに置き換えます。

これは私がPythonスクリプトに変換したいのコード例です:

int a = foo[0]; 
int b = foo[1]; 
int c = foo[2]; 

これは、変換後に所望の結果である:列挙型の交換のため

int a = bar(enum_zero); 
int b = bar(enum_one); 
int c = bar(enum_two); 

Pythonの辞書:

enums = dict([('zero',0), 
       ('one', 1), 
       ('two', 2)]) 

これは、配列をfに置き換えることができる現在の非機能です列挙型と慰めではなく数:

import fileinput 
import re 

enums = dict([('zero',0), 
       ('one', 1), 
       ('two', 2)]) 

search = r'foo' 
replace = r'bar' 

read = open('test.cpp', 'r') 
write = open('out.cpp', 'w') 

for line in read: 
    if line.find(search) != -1: 
     s_tag = r'(\-)('+search+r')\[(\d+)\](?=\.\w+)' 
     r_tag = r'\1'+replace+r'(\3)' 
     line = re.sub(s_tag, r_tag, line, re.M) 
     write.write(line) 
    else: 
     write.write(line) 

read.close() 
+0

「サンプルコード」を「希望のコード」に変換したい – dgrat

答えて

1

あなたの辞書や使用のグループを変更する場合には、物事を単純化するかもしれません():

import fileinput 
import re 

replacements = {0: 'zero', 1: 'one', 2: 'two'} 

variable = r'foo' 
function = r'bar' 

read = open('test.cpp', 'r') 
write = open('out.cpp', 'w') 

for line in read: 
    m = re.match(r'(.*)' + variable + r'\[(\d+)]', line) 
    if m: 
     start, key = m.groups() 
     modified = '{start}{function}({replacement});\n'.format(
      start=start, 
      function=function, 
      replacement=replacements[int(key)] 
     ) 
     write.write(modified) 
    else: 
     write.write(line) 

read.close() 
2

これは、すべてのように、単一のre.sub()コールを使用して行うことができます次の:

import re 

search = r'foo' 
replace = r'bar'  
s_tag = r'\b(' + search + r') *?\[ *?(\d+) *?\]' 
enums = {'0':'enum_zero', '1':'enum_one', '2':'enum_two'} 

with open('test.cpp') as f_cpp: 
    text = f_cpp.read() 

with open('out.cpp', 'w') as f_out:  
    f_out.write(re.sub(s_tag, lambda x: "{}({})".format(replace, enums[x.group(2)]), text)) 

はあなたの出力ファイル与える:

int a = bar(enum_zero); 
int b = bar(enum_one); 
int c = bar(enum_two); 

ラムダ関数を使用して、enums辞書を使用して必要な置換を検索し、出力を適切な関数呼び出し形式にフォーマットします。

withを使用すると、後で明示的にファイルを閉じる必要はありません。

関連する問題