一、需求
scan0 -------------------------scan[0]
scan1 -------------------------scan[1]
scan2 -------------------------scan[2]
scan5 ----------变成---------scan[5]
scan22 ------------------------scan[22]
fuck ----------------------------fuck
fu123ck------------------------fu123ck
二、实现思想
用替换的方式,把字符串最后的数字替换成[数字]。
三、需要的库
re
四、正则匹配
正则表达式pattern= r’(.*\D)(\d+$)’
其中第一个()表示scan字符串
第二个()表示数字
五、替换
替换用re.sub
替换完的字符串 = re.sub(r’(.*\D)(\d+$)’, r’\1[\2]’, 要替换的字符串)
六、参考代码
import openpyxl
import re
def read_exl(j):
wb = openpyxl.load_workbook(r"C:\Users\lenovo\Desktop\mapping.xlsx")
ws = wb['123']
in_lst = []
in_lst_pin = []
out_lst = []
out_lst_pin = []
for i in range(2, 138):
a = ws.cell(row=i, column=4 + j).value
if a in ["input", "inout"]:
mbist = ws.cell(row=i, column=3 + j).value
pattern = r'(.*\D)(\d+$)'
l = re.findall(pattern, mbist)
if l:
mbist_new = re.sub(pattern, r'\1[\2]', mbist)
in_lst.append(mbist_new)
else:
in_lst.append(mbist)
pin = ws.cell(row=i, column=2).value
in_lst_pin.append(pin)
for i in range(2, 138):
a = ws.cell(row=i, column=4 + j).value
if a in ["output", "inout", "output-z"]:
mbist = ws.cell(row=i, column=3 + j).value
pattern = r'(.*\D)(\d+$)'
l = re.findall(pattern, mbist)
if l:
mbist_new = re.sub(pattern, r'\1[\2]', mbist)
out_lst.append(mbist_new)
else:
out_lst.append(mbist)
pin = ws.cell(row=i, column=2).value
out_lst_pin.append(pin)
in_lst = str(in_lst)
in_lst_pin = str(in_lst_pin)
out_lst = str(out_lst)
out_lst_pin = str(out_lst_pin)
in_lst = in_lst.replace('\'', '"')
in_lst_pin = in_lst_pin.replace('\'', '"')
out_lst = out_lst.replace('\'', '"')
out_lst_pin = out_lst_pin.replace('\'', '"')
in_lst = re.sub(r'(\[)(.*)(\])', r'\2', in_lst)
in_lst_pin = re.sub(r'(\[)(.*)(\])', r'\2', in_lst_pin)
out_lst = re.sub(r'(\[)(.*)(\])', r'\2', out_lst)
out_lst_pin = re.sub(r'(\[)(.*)(\])', r'\2', out_lst_pin)
print(in_lst)
print(in_lst_pin)
print(out_lst)
print(out_lst_pin)
write_txt(in_lst, in_lst_pin, out_lst, out_lst_pin, j)
def write_txt(in_lst, in_lst_pin, out_lst, out_lst_pin, j):
f = open(r"C:\Users\lenovo\Desktop\123.txt", "a")
f.write("" + "\n")
f.write("%d : begin" % k + "\n")
f.write("string input_scan_name[] = " + "{" + in_lst + "}" + ";" + "\n")
f.write("string input_pad_name[] = " + "{" + in_lst_pin + "}" + ";" + "\n")
f.write("string output_scan_name[] = " + "{" + out_lst + "}" + ";" + "\n")
f.write("string output_pad_name[] = " + "{" + out_lst_pin + "}" + ";" + "\n")
f.write("end" + "\n")
f.close()
for k in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
j = k * 2
read_exl(j)