2017-09-24 12 views
1

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

+1

あなたは 'line'変数の変更は、' lines'を修正しない、 'lines'リストを変更しないでください。 –

+0

はい!それを見つけてくれてありがとう! – Lancophone

答えて

0
にコードを変更し

:あなたは正規表現をコンパイルし、動作しませんこれは、後で文字列としてそれを使用しようとしていた

regex = re.compile(r">>>>>{(\w+)}") 
for line in lines: 
    line = regex.sub(replace_key_vals, line) 
    #  ---^--- 

+0

この回答は@Janでは機能しません。私は同じエラーを受け取ります – Lancophone

+0

@Lancophone:いくつかの入力文字列がありますか? – Jan

+0

この問題は修正されました。実際には私が 'match.string()'を呼び出していたことが原因でした。そのクラスメンバーであり、関数ではありません。しかし、新しい問題は、コードで実行時エラーが発生するわけではありませんが、実際にはテンプレートから出力ファイルを作成するときに何も置き換えられないということです – Lancophone

0

次のコードは、私の問題を修正:

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): 
     print match.string 
     for key, value in template_keys.iteritems(): 
      if key in match.string: 
       return value 

    regex = re.compile(r">>>>>{(\w+)}") 
    # for line in lines: 
     # line = regex.sub(replace_key_vals, line) 
    lines = [regex.sub(replace_key_vals, line) for line in lines] 

    with open(os.path.join(self.project_root, 'CMakeLists.txt'), 'w') as cmake_file: 
     cmake_file.writelines(lines) 
関連する問題