>我有一个文本文件,我已经在与某种模式匹配的行列表中将其处理为字符串。我想用列表中的元组替换行的匹配部分
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)
但它提出了一个错误 类型错误:"str"对象不能在位置换行符处解释为整数。
第一次尝试:
- 如果你在调试器中查看
str(k)
,你会发现这不是一行k
,而是整个数组的字符串表示形式,参见str。 - 在正则表达式中,仅匹配要替换的文本部分,请参阅 re.sub。
第二次尝试:
- 您正在传递一个元组作为替换,它应该是字符串或函数(请参阅下面的示例中的连接(。
下面的示例使用 zip 循环访问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