2012-04-29 161 views
-2

靜態常量替換的#define我是一個新手,蟒蛇,願與下面的任務幫助:與蟒蛇

給定一個H/CPP文件我想,以取代靜態常量各的#define行。 當然,變量的類型應該是正確的(可以說只有int或字符串)。

我該怎麼做?

+0

你在編輯h/cpp文件嗎?你想加載它們在python中運行嗎? –

+0

我正在編輯它們 –

+0

這是一次性的事情嗎?我無法想象這會出現很多。你可以使用任何好的編輯器輕鬆找到/替換。 –

回答

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) 
+0

像這樣的東西,可能需要一些小修改,但概念在那裏。 – chameco

+0

我想「新」不是Python中的關鍵字,但將它作爲變量仍然讓我畏懼 –

+0

哈哈,對不起。我尊重新的神聖性,但我很習慣使用匯編,因爲你必須以「.data」的形式訪問它,因此我唯一真正感到畏懼的是具有「數據」屬性的類。 – chameco

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模塊。