简体   繁体   English

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

[英]Replace python regular expression with string from a dictionary

I'm trying to create a file from a template file. 我正在尝试从模板文件创建文件。 The template has a few elements that need to be dynamically set based on user input or from a config file. 该模板具有一些元素,需要根据用户输入或从配置文件动态设置。 The template contains instances of the regex I have in the code below. 模板包含以下代码中包含的正则表达式的实例。 What I want to do is simply replace the word (\\w) contained in the regex with a know value from a dictionary. 我想做的就是简单地将正则表达式中包含的单词(\\w)替换成字典中的已知值。 Below is my code: 下面是我的代码:

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)

The python interpreter complains with TypeError: 'str' object is not callable . python解释器抱怨TypeError: 'str' object is not callable I'd like to know why this code doesn't work, and a way to fix it. 我想知道为什么此代码不起作用,以及修复它的方法。

Change your code to: 将您的代码更改为:

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

You were compiling the regular expression and were trying to use it as a string afterwards, which won't work. 您正在编译正则表达式,然后尝试将其用作字符串,这将不起作用。

The following code fixed my problem: 以下代码解决了我的问题:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM