Python 如何用元组列表替换列表中正则表达式匹配的模式?

Python 如何用元组列表替换列表中正则表达式匹配的模式?,python,regex,python-3.5,Python,Regex,Python 3.5,我有一个文本文件,我把它作为字符串处理在一个匹配特定模式的行列表中。我想用列表中的元组替换行中匹配的部分 D= ['M2 (net23 Vin\\- net20 0) nmos1', 'M1 (net19 Vin\\+ net20 0) nmos1', 'M7 (vout\\- net29 0 0) nmos1', 'M5 (net20 net29 0 0) nmos1' , 'NM4 (net29 net29 0 0) nmos1', 'N

我有一个文本文件,我把它作为字符串处理在一个匹配特定模式的行列表中。我想用列表中的元组替换行中匹配的部分

 D= ['M2 (net23 Vin\\- net20 0) nmos1',
     'M1 (net19 Vin\\+ net20 0) nmos1', 
     'M7 (vout\\- net29 0 0) nmos1',
     'M5 (net20 net29 0 0) nmos1' ,
     'NM4 (net29 net29 0 0) nmos1',
     'NM3 (net22 net29 0 0) nmos1' ]
我写了一个生成

k = [('breach', 'Vin\\-', 'net20', '0'),
     ('net19', 'Vin\\+', 'net20', '0'),
     ('vout\\-', 'net29', '0', '0'),
     ('net20', 'net29', '0', '0'),
     ('net29', 'net29', '0', '0'),
     ('net22', 'net29', '0', '0')]
我需要输出为

['M2 (breach Vin\\- net20 0) nmos1',
 'M1 (net19 Vin\\+ net20 0) nmos1', 
 'M7 (vout\\- net29 0 0) nmos1',
 'M5 (net20 net29 0 0) nmos1',
 'NM4 (net29 net29 0 0) nmos1',
 'NM3 (net22 net29 0 0) nmos1' ]
我可以手动执行此操作,但我希望对其中的所有节点执行此操作,一次一个

我试过了

cmos_regex_pattern = re.compile('(.*) (\(.*\)) (nmos1|pmos1) ((.*))')
for line in D:
   data = cmos_regex_pattern.search(line)
   if data:
       re.sub(cmos_regex_pattern,str(k),data.group(2))
到目前为止,但它没有做任何事情

另一件事,我累了

    regex_pattern = re.compile('(.*) (\(.*\)) (nmos1|pmos1) ((.*))')
    for i in range(len(D)):
         find = D[i]
         #print(find)
         replace = k[i]
         #print(replace)
         for line in D:
         print (line)
         new_line = regex_pattern.sub(find,replace,line)
但它出现了一个错误 TypeError:“str”对象不能在换行位置解释为整数。

第一次尝试:

  • 如果查看调试器中的
    str(k)
    ,您将看到这不是
    k
    的一行,而是整个数组的字符串表示形式,请参阅
  • 在正则表达式中,仅匹配要替换的文本部分,请参见
第二次尝试:

  • 您将一个元组作为replace传递,该元组应该是字符串或函数(请参见下面的示例)
以下示例用于迭代
D
/
k
组合。如果您的数据不如所示示例中的数据一致,则可能需要对此进行调整

result = []
cmos_regex_pattern = re.compile('(\(.*\))') # the pattern that matches the text which should be replaced
for k_data, line in zip(k, D):
    k_str = "(" + " ".join(k_data) + ")" # the text which replaces the matched text
    result.append(re.sub(cmos_regex_pattern, k_str, line)) # perform the replacement in the current line, and add the result to the 'result' array

Total\u Mos\u device
中显示的内容不是有效的Python语法,请提出问题并解决此问题。我们需要看一个。谢谢你指出我例子中的错误。我把它改成了一个可重复性最低的例子。