テンプレートファイルからファイルを作成しようとしています。 テンプレートには、ユーザー入力または設定ファイルに基づいて動的に設定する必要のあるいくつかの要素があります。 テンプレートには、以下のコードにある正規表現のインスタンスが含まれています。 私がしたいのは、正規表現に含まれている単語(\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
と文句を言う: 以下は私のコードです。 このコードがなぜ機能しないのか、それを修正する方法を知りたいのですが。
あなたは 'line'変数の変更は、' lines'を修正しない、 'lines'リストを変更しないでください。 –
はい!それを見つけてくれてありがとう! – Lancophone