1

私は本当に Python が初めてで、#define 変数の値を変更するスクリプトを作成しようとしています。私のコードは機能しているように見えますが、出力ファイルの C インデントが台無しになります。では、空白の問題を回避するにはどうすればよいですか? 私よりもスマートな実装の提案は大歓迎です!

KEYWORDS=["PERIOD","PWM_RATE","DUTY_OFFSET","MAX_DUTY"]
VALS=[3,3,3,3]    
import re
f1 = open('../src/in.c','r')
f2 = open('../src/out.xc','w')
for line in f1:
    s=line.split()
    if len(s)> 1 and s[1] in KEYWORDS:
        s[2] = VALS[1]
    f2.write(' '.join(s)+'\n')
f1.close()
f2.close()
4

4 に答える 4

3

行内の単語間の元の間隔を維持するために使用regexします。

withファイルを自動的に閉じるため、ファイルを処理するステートメントを使用します。

with open('../src/in.c','r') as f1, open('../src/out.xc','w') as f2:
    for line in f1:
        if line.startswith("#define"):
            s=line.split()
            if s[1] in KEYWORDS:
                val = str(VALS[1])
                line = re.sub(r'({0}\s+)[a-zA-Z0-9"]+'.format(s[1]),r"\g<1>{0}".format(val),line)
        f2.write(line)

入力:

#define PERIOD  100
#define PWM_RATE  5
#define DUTY_OFFSET  6
#define MAX_DUTY             7
#define PERIOD 2     5000000

#include<stdio.h>  
int main()  
{  
    int i,n,factor;  
    printf("Enter the last number of the sequence:");  
    scanf("%d",&j);
} 

出力:

#define PERIOD  3
#define PWM_RATE  3
#define DUTY_OFFSET  3
#define MAX_DUTY             3
#define PERIOD 3     5000000

#include<stdio.h>
int main()
{
int i,n,factor;
printf("Enter the last number of the sequence:");
scanf("%d",&j);
}
于 2013-05-16T19:05:13.077 に答える