我試圖從模板文件創建一個文件。 該模板有幾個元素需要根據用戶輸入或配置文件進行動態設置。 該模板包含我在下面的代碼中的正則表達式的實例。 我想要做的就是用正確的字典替換正則表達式中包含的(\w)
這個單詞。 下面是我的代碼:用字典中的字符串替換python正則表達式
def write_cmake_file(self):
# pass
with open (os.path.join(os.getcwd(), 'templates', self.template_name)) as f:
lines = f.readlines()
def replace_key_vals(match):
for key, value in template_keys.iteritems():
if key in match.string():
return value
regex = re.compile(r">>>>>{(\w+)}")
for line in lines:
line = re.sub(regex, replace_key_vals, line)
with open(os.path.join(self.project_root, 'CMakeLists.txt'), 'w') as cmake_file:
cmake_file.write(lines)
Python解釋器TypeError: 'str' object is not callable
抱怨。 我想知道爲什麼這段代碼不起作用,並且有一種解決方法。
你不改變'lines'列表,'line'變量的變化不會修改'lines'。 –
是的!感謝您發現! – Lancophone