demand : Will xmind File to Excel Archives , And new UI Interface operation to reduce the difficulty of operation .
This requirement can be made clear in one sentence , But there is actually a lot of work to be done :
1, Understanding Xmind File structure
2, extract Xmind File branch content ( Emphasis )
3,UI Interface ( It's not necessary )
1,xmind File form : Tree branch structure ( Think about how to extract the content of each branch first ).
Excel Extract what form : The trunk is connected to the branch , use “\” Line number one .( After understanding the principle, you can write it in any other form you want )
Examples :
https\Tunnel to Meaning \Tunnel( Tunnel ), Intermediate entities
https\Tunnel to Meaning \ Hiding : Rules - Hidden connection
So how to analyze the above data structure for the specific ? use “from xmindparser import xmind_to_dict”, use xmindparser The package converts it into a dictionary format and processes it .
Another example :
This xmind The file passed through xmind_to_dict What can be converted into ?
{'title': 'A', 'topics': [{'title': 'B1'}, {'title': 'B2', 'topics': [{'title': 'C1'}, {'title': 'C2'}]}, {'title': 'B3'}]}
Still not intuitive enough , use json The analyzer expands and looks at :
[
{
'title': ' Canvas 1',
'topic': {
'title': 'A',
'topics': [
{
'title': 'B1'
},
{
'title': 'B2',
'topics': [
{
'title': 'C1'
},
{
'title': 'C2'
}
]
},
{
'title': 'B3'
}
]
},
'structure': 'org.xmind.ui.map.unbalanced'
}
]
The content is installed in one list Li , The outer layer of the dictionary title For “ Canvas 1”,topic With what we need ( You can see that other places are called topics), This is xmind What's not in the file , It was verified that this is a fixed value , You can ignore . And then by taking list,A It's in the dictionary value value ,key For title, Its child nodes are installed in topics In the branch of . After processing, it's like this , The outermost layer is dict:
That's the problem , How to treat it as the desired form ? Layer by layer key、value Do you ?
Of course not , That workload will be very large , And it is not good for reading and modifying . Remember what I thought about ? Here we need to use what you think , That's right , Recursion .
Why to use the recursive , Let's look at the structure :
A The three sub nodes of are B1,B2,B3,B2 The child node of is C1C2, See the picture and you think about something ?
1, The title and child nodes are placed in different item Li , namely topic Put the root node , that topics And then put its child nodes .
2,topics No child nodes ? image C1C2 There are no child nodes at that point , We found that , It doesn't have topics; At the same time , No child node proves that it is the last layer of this branch ; Just imagine , If A No child nodes , It's just one ? As you think , It has only one title, No topics.
3,A The child node of is a list,list There can be multiple child nodes , If there are children, there are topics, If not, then not topics.
4,title Always pretend to be string, and topics You can put list,list There's still dict, There can be no topics.
I still feel very confused after seeing four o'clock ?
We need to take the child nodes one by one to get what we want A\B2\C1、A\B2\C2, Node value is always title Li , And the child nodes are in dict、list Inside dict Li , And there is only one of the children title, Yes, there is one title Add one topics, As has been said before , Yes topics There are also its children .
So now it should be clear ? It's not clear ? That virtual code is going to be over again :
If Input Dictionary :
When the dictionary has only title When :
operation 1
When the dictionary has title and topics When :
operation 2
If Input list:
Traversal list The dictionary in :
Operate on each dictionary 3
If It is not a dictionary or a list:
Output value
The framework of ideas has been built , That operation 1、2、3 What is it ? In fact, it is the repeated operation of this framework , Call yourself , It is not strict to say that this is a recursive popular explanation .
We post code :
1 def TraversalXmind(root,rootstring): 2 if isinstance(root, dict): 3 if len(root) == 2: 4 TraversalXmind(root['topics'], str(rootstring) ) 5 if len(root) == 1: 6 TraversalXmind(root['title'],str(rootstring) ) 7 8 elif isinstance(root, list): 9 for sonroot in root: 10 TraversalXmind(sonroot, str(rootstring) + "\\" + sonroot['title']) 11 12 elif isinstance(root,str): 13 print(str(rootstring) ) 14 15 # TraversalXmind(root, "\\AA")
What is the full code ?
Uninstall the conversion process described above model.py in :
1 # -*-coding:utf-8 -*- 2 # Author : zhengyong 3 # Time : 2020/11/5 23:06 4 # FileName: model.py 5 6 from xmindparser import xmind_to_dict 7 import os,csv 8 # filepath1 = os.path.abspath(os.path.dirname(__file__)) 9 # print(filepath1) 10 11 # filepath = "D:\\test.xmind" 12 # inputedXmind = xmind_to_dict(filepath) 13 # root = inputedXmind[0]['topic'] 14 15 def traversalXmind(root, rootstring,lisitcontainer): 16 """ 17 function : Recursion dictionary Files are easy to write to Excel The form of form . 18 Be careful :rootstring Use both str To handle Chinese characters 19 @param root: Will xmind After treatment dictionary Archives 20 @param rootstring: xmind The root title 21 """ 22 if isinstance(root, dict): 23 if len(root) == 2: 24 traversalXmind(root['topics'], str(rootstring),lisitcontainer) 25 if len(root) == 1: 26 traversalXmind(root['title'], str(rootstring),lisitcontainer) 27 28 elif isinstance(root, list): 29 for sonroot in root: 30 traversalXmind(sonroot, str(rootstring) + "\\" + sonroot['title'],lisitcontainer) 31 32 elif isinstance(root, str): 33 lisitcontainer.append(str(rootstring)) 34 35 def getCase(root): 36 rootstring = root['title'] 37 lisitcontainer = [] 38 traversalXmind(root, rootstring,lisitcontainer) 39 # print(lisitcontainer) 40 return lisitcontainer 41 42 # def getTestCase(filename,lisitcontainer,directory,group,runType,testcaseType,testType): 43 # header = [ 44 # ' Test case path ', 45 # ' Test case name ', 46 # ' Test case description ', 47 # ' How long does the plan take ( Minutes )', 48 # ' Step description ', 49 # ' Expected results ', 50 # ' Priorities ', 51 # ' Group ', 52 # ' Way of execution ', 53 # ' Test module ', 54 # ' Version number ', 55 # ' Use case types ', 56 # ' Test type ', 57 # ' Related story cards ID', 58 # ] 59 # 60 # with open(filename,'w',newline='') as f: 61 # writer = csv.DictWriter(f,fieldnames=header), 62 # writer.writeheader() 63 # for row in lisitcontainer: 64 # writer.writerow({ 65 # ' Test case path ': directory, 66 # ' Test case name ': row, 67 # ' Group ': group, 68 # ' Way of execution ': runType, 69 # ' Use case types ':testcaseType, 70 # ' Test type ': testType, 71 # })
UI The interface uses tkinter It's written , Go straight to the code :
1 #-*-coding:utf-8 -*- 2 # Author : zhengyong 3 # Time : 2020/11/14 23:54 4 # FileName: main1.py 5 # https://github.com/ndnmonkey/transXmindToCSV.git 6 7 import model 8 from xmindparser import xmind_to_dict 9 import tkinter 10 from tkinter import filedialog 11 from tkinter import * 12 import os,csv 13 14 15 window = tkinter.Tk() 16 window.title(" Use case export tool ") 17 # Set the window icon 18 # window.iconbitmap("D:\Code\Python\XmindToExcel\image\icon.ico") 19 # window.iconbitmap("image\ifavicon.ico") 20 window.geometry("400x370+200+50") 21 22 # Title 23 labeltitle = tkinter.Label(window,text = " Use case export tool ",font = (' Young round ',20)).pack() 24 25 # Create a menu bar 26 MenuBar = tkinter.Menu(window) 27 # Put the menu bar in the main window 28 window.config(menu=MenuBar) 29 # Create a file menu , Don't show windows 30 fileBar = tkinter.Menu(MenuBar, tearoff=0) 31 # Add file menu item 32 fileBar.add_command(label=" Directions ") 33 # fileBar.add_command(label=" Contact the author ") 34 # Create a split line 35 # fileBar.add_separator() 36 fileBar.add_command(label=" sign out ", command=window.destroy) 37 # Add file menu to menu column 38 MenuBar.add_cascade(label=" menu ", menu=fileBar) 39 40 xlabe = 20 41 xtext = 80 42 y =10 43 step = 30 44 textwidth = 250 45 46 inputtext1 = tkinter.StringVar(value='\ General version use cases \ Current version name \ full name \ Demand name ') 47 labe1 = tkinter.Label(window, text=' Use case paths :').place(x=xlabe,y = y + step) 48 text1 = tkinter.Entry(window, show=None, textvariable=inputtext1) 49 text1.place(width=textwidth,x=xtext+ 1*step,y=y + step) 50 51 inputtext2 = tkinter.StringVar(value=' Team leader's name ') 52 labe2 = tkinter.Label(window, text=' Name of the team leader :').place(x=xlabe,y=y + 2*step) 53 text2 = tkinter.Entry(window, show=None, textvariable=inputtext2) 54 text2.place(width=textwidth,x=xtext+ 1*step,y=y + 2*step) 55 56 inputtext3 = tkinter.StringVar(value=' Manual testing ') 57 labe3 = tkinter.Label(window, text=' Way of execution :').place(x=xlabe,y=y + 3*step) 58 text3 = tkinter.Entry(window, show=None, textvariable=inputtext3) 59 text3.place(width=textwidth,x=xtext+ 1*step,y=y + 3*step) 60 61 inputtext4 = tkinter.StringVar(value=' System use cases ') 62 labe4 = tkinter.Label(window, text=' Use case types :').place(x=xlabe,y=y + 4*step) 63 text4 = tkinter.Entry(window, show=None, textvariable=inputtext4) 64 text4.place(width=textwidth,x=xtext+ 1*step,y=y + 4*step) 65 66 inputtext5 = tkinter.StringVar(value=' Manual testing ') 67 labe5 = tkinter.Label(window, text=' Test type :').place(x=xlabe,y=y + 5*step) 68 text5 = tkinter.Entry(window, show=None, textvariable=inputtext5) 69 text5.place(width=textwidth,x=xtext+ 1*step,y=y + 5*step) 70 71 def getTextValues(): 72 templist = [] 73 var1 = text1.get();templist.append(var1) 74 var2 = text2.get();templist.append(var2) 75 var3 = text3.get();templist.append(var3) 76 var4 = text4.get();templist.append(var4) 77 var5 = text5.get();templist.append(var5) 78 # print("1",templist) 79 return templist 80 81 casebutton1 = tkinter.Button(window,text = '1, Submit use case information ',width=5,height=1,command=getTextValues) 82 casebutton1.place(x=110,y=y + 6*step) 83 casebutton1.configure(width = 34, height = 2) 84 85 def open_file(): 86 templist = getTextValues() 87 # print("2",templist) 88 filename = filedialog.askopenfilename(title=' Turn on Xmind Archives ', filetypes=[('xmind', '*.xmind')]) 89 90 entry_filename.delete(0, END) 91 entry_filename.insert('insert', filename) 92 # print(entry_filename,type(entry_filename)) 93 94 # print(filename) 95 fname = entry_filename.get() # use get extract entry Content in 96 fname = str(fname).replace('/','\\\\') 97 # print("fname",fname) 98 99 # filepath = "D:\\test.xmind" 100 # inputedXmind = xmind_to_dict(filepath) 101 # root = inputedXmind[0]['topic'] 102 # 103 inputedXmind = xmind_to_dict(fname) 104 root = inputedXmind[0]['topic'] 105 lisitcontainer = model.getCase(root) 106 # print(lisitcontainer) 107 108 # templist 109 directory = templist[0] 110 group = templist[1] 111 runType = templist[2] 112 testcaseType = templist[3] 113 testType = templist[4] 114 # filename = 'testcase.csv' 115 header = [ 116 ' Test case path ', 117 ' Test case name ', 118 ' Test case description ', 119 ' How long does the plan take ( Minutes )', 120 ' Step description ', 121 ' Expected results ', 122 ' Priorities ', 123 ' Group ', 124 ' Way of execution ', 125 ' Test module ', 126 ' Version number ', 127 ' Use case types ', 128 ' Test type ', 129 ' Related story cards ID', 130 ] 131 # print(filename) #D:\\test.xmind 132 savepath = fname.split('.')[0] + ".csv" 133 # print("savepath:",savepath) 134 135 with open(savepath, 'w', newline='') as f: 136 writer = csv.DictWriter(f, fieldnames=header) 137 writer.writeheader() 138 for row in lisitcontainer: 139 writer.writerow({ 140 ' Test case path ': directory, 141 ' Test case name ': row, 142 ' Group ': group, 143 ' Way of execution ': runType, 144 ' Use case types ': testcaseType, 145 ' Test type ': testType, 146 }) 147 148 # Set button Button accept function 149 importbutton = tkinter.Button(window, text="2, Import Xmind Archives ", command=open_file) 150 importbutton.place(x=110,y=y + 9*step) 151 importbutton.configure(width =34,height=2) 152 153 # Set entry 154 entry_filename = tkinter.Entry(window, width=30, font=(" Song style ", 10, 'bold')) 155 entry_filename.place(width=textwidth,x=xtext+ 1*step,y=y + 8*step) 156 157 # Copyright page 158 labelright = tkinter.Label(window,text = "version 0.3 bug Restoration :[email protected]",font = (' Song style ',8)).place(x=60,y=350) 159 # Tk().iconbitmap('D:\Code\Python\XmindToExcel\image\icon.ico') 160 window.mainloop()
Then there is a question at this time , What is the result of the execution ?
use pyinstaller You can package code files into executable files :
Method :
1, Install pyinstaller( I don't want to be specific about )
2, Use :
Command line :
pyinstaller -F Master file name .py
What if the executable file has a black box ?
pyinstaller -F -w mycode.py (-w It's just to cancel the window )
3, Where is the generated executable file ?
In the master file folder dist in ,
4, Specific file structure :
All code is original , Because I can't find the available tutorials , Learn the hardships of finding a tutorial , So, we can give up some ideas , My level is limited , If there's something wrong with the article and the code , Please give me some advice , You can talk about it .
Welcome to reprint , Please indicate the following :
I am cnblogs Upper ID For puppet Lolo , The blog address is https://www.cnblogs.com/two-peanuts/ All blogs containing original announcement are my original works . Blog content except the cited literature has been noted are my independent research results . Unless otherwise specified, it shall be used Knowledge sharing A signature - Non commercial use - Share in the same way 3.0 Mainland China License agreement to license .
The specific file structure has been transmitted to github,github Address :https://github.com/ndnmonkey/transXmindToCSV , Welcome star.
&n