2017-09-24 189 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

你不改變'lines'列表,'line'變量的變化不會修改'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) 
相關問題