-2

私はPythonの初心者で、次のタスクについて助けてください:

ah/cpp ファイルを指定して、各 #define 行を static const に置き換えたいと思います。もちろん、変数の型は正しいはずです (int または string のみとしましょう)。

どうやってやるの?

4

2 に答える 2

1
new = ""
file = open("file.cpp")
for line in file:
    if "#define" in file:
        splitline = line.split(" ")
        new += "static const "
        if '"' in line:
            new += "string "
        else:
            new += "int "
        new += splitline[1]
        new += " = "
        new += splitline[2]
        new += ";\n"
    else:
        new += line + "\n"
file.close()
newfile = open("new.cpp")
newfile.write(new)
于 2012-04-29T19:37:54.633 に答える
0
import sys

# Read in the file as an array of lines
lines = file(sys.argv[1], 'r').readlines()

# Loop over the lines and replace any instance of #define with 'static const'
for line_no in xrange(len(lines)):
    lines[line_no] = lines[line_no].replace('#define', 'static const')

# Write the file back out
file(sys.argv[1], 'w').writelines(lines)

そして、はい、ループをリスト内包表記に置き換えることもできますが、Python を初めて使用する人にとっては、これはより明確です。リスト内包版は次のとおりです。

lines = [line.replace('#define', 'static const') for line in file(sys.argv[1], 'r').readlines()]
file(sys.argv[1], 'w').writelines(lines)

これらの例は型を考慮していませんが、このようなものを自動的に置き換えることは、おそらく恐ろしい見通しです。他の誰かが指摘したように、テキスト エディターを使用して、自分が行っていることが実際に正しいことを確認する必要がありますが、一般的には、これが検索と置換の方法です。

別の実装では、正規表現を使用します。そのために re モジュールをインポートします。

于 2012-04-29T19:39:54.050 に答える