用字典中的字符串替换python正则表达式

问题描述:

我试图从模板文件创建一个文件。 该模板有几个元素需要根据用户输入或配置文件进行动态设置。 该模板包含我在下面的代码中的正则表达式的实例。 我想要做的就是用正确的字典替换正则表达式中包含的(\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

你不改变'lines'列表,'line'变量的变化不会修改'lines'。 –

+0

是的!感谢您发现! – Lancophone

你的代码更改为:

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

下面的代码固定我的问题:

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)