如何用元组列表替换列表中与regex匹配的模式?

2024-04-23 22:23:02 发布

您现在位置:Python中文网/ 问答频道 /正文

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

 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”对象不能在换行位置处解释为整数。你知道吗


Tags: inrefordatalineregexpatterncmos
1条回答
网友
1楼 · 发布于 2024-04-23 22:23:02

第一次尝试:

  • 如果您在调试器中查看str(k),您将看到这不是一行k,而是整个数组的字符串表示,请参见str。你知道吗
  • 在regex中,只匹配要替换的文本部分,请参见re.sub。你知道吗

第二次尝试:

  • 您正在传递一个元组作为replace,它应该是字符串或函数(请参见下面示例中的join)。你知道吗

下面的示例使用zipD/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

相关问题 更多 >