1、實現的功能:
根據test.xlsx中輸入的的信息如下圖1,首先先生成圖2中test.v的代碼,然后正則匹配test.v中的代碼,並將其例化后寫入到top.v中如圖3。

圖1 test.xlsx 圖2 test.v 圖3 top.v
2、工程鏈接代碼:https://files.cnblogs.com/files/aslmer/verilog_gen.rar
import os import re import openpyxl excel_name= "test.xlsx" input_file= os.getcwd()+"\\"+excel_name #1、打開excel的工作表 wb = openpyxl.load_workbook(input_file) #2、獲取工作表的名字test,返回的是一個list module_name= wb.sheetnames #3、list轉為str top_name=''.join(module_name) #生成一個test.v,其中寫入的是將test.xlsx中的信息轉化為verilog的代碼框架 gen_file= os.getcwd()+"\\"+top_name+'.v' #每次運行的時候檢測test.v是否存在,如果存在則刪除 if os.path.exists(gen_file): os.remove(gen_file) print(''.join(module_name))#list ---> str #打開excel名字為test的工作表 table= wb[top_name] #open sheet by name #統計表格中的行數和列數 row_num = table.max_row col_num = table.max_column ##定義列表變量 ##端口名字 clk rst_n din dout port_name=[] ##位寬 1 1 4 3 port_width=[]## ## 端口方向 input output inout port_type=[] for i in range(row_num): port_name.append(table.cell(row=i+1, column=1).value)##excel中的第一列 port_type.append(table.cell(row=i+1,column=2).value)##excel中的第二列 port_width.append(table.cell(row=i+1,column=3).value)##excel中的第三列 print(port_name) print(port_type) print(port_width) ##打開test.v並寫入從excel信息對應的verilog代碼 with open(gen_file,'a') as file_obj: file_obj.write('module '+top_name+'(\n') for i in range(row_num-1): if(port_type[i+1] == "I"): port_str="input" elif(port_type[i+1] == "O"): port_str='output' if(port_width[i+1]== 1): width_str=" " else: width_str=" ["+str(port_width[i+1]-1)+':0]' if(i<row_num-2): file_obj.write(port_str+" wire "+width_str +port_name[i+1]+',\n') else: file_obj.write(port_str +" wire " + ' [' + str(port_width[i + 1] - 1) + ':0]' + port_name[i + 1] + '\n );\nendmodule') ##正則匹配re,獲取需要的信息 \s代表空格、制表符、換行符 + 前面的字符一個或一個以上 \w代表數字、字母、下划線 # *代表重復次數為0~無限多次 |或 +:至少1個~更多個 ?代表前面的字符可以是0個或者最多1個 #對於標點符號比如 減號- 方括號[] 冒號:均需要用反斜杠\進行轉義 acquire_module=re.compile('(module)(\s+)(\w+)') acquire_ports =re.compile(".*(input|output|inout)(\s+)(wire|reg)?(\s+)(\[\w+\:0\])?(\w+)") with open(gen_file,'r') as file_obj: content = file_obj.read()#d讀取test.v文件中的所有內容 print(content) module_obj = acquire_module.search(content)#從test.v中匹配到需要的字符串,search只返回一個匹配的結果 port_obj =acquire_ports.findall(content) #findall返回所有的匹配結果,返回一個list類型 print( module_obj.group(3))#group用()進行分組,group(0)或者group()代表所有組的集合,group(1)代表第一組(),依次遞增 print(port_obj,type(port_obj)) ##1、打開一個文件top.v,將產生的test.v文件進行例化 inst_file=os.getcwd()+"\\top.v" if os.path.exists(inst_file): os.remove(inst_file) print(inst_file) with open(inst_file,'a')as fp: fp.write(module_obj.group(3)+" u_"+module_obj.group(3)+'\n(\n') for i in range(len(port_obj)): if(i<len(port_obj)-1): fp.write(' .'+port_obj[i][5]+' ('+port_obj[i][5]+'),\n') else: fp.write(' .' + port_obj[i][5] + ' (' + port_obj[i][5] + ')\n);\n')
一直斷斷續續,重蹈覆轍的說要學python,學習又放棄,這也許是第一個堅持寫出來的自己想要的小工具,雖然可能方法很笨拙,也算是邁出了第一步。
