From Python XMIND to excel

Puppet Lolo 2020-11-15 13:06:27
python xmind excel


demand : take xmind The file to Excel file , And add 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, understand Xmind File structure

2, extract Xmind File branch content ( a key )

3,UI Interface ( It's not necessary )

One , understand Xmind File structure

1,xmind File form : Tree branch structure ( Think about how to extract the content of each branch first ).

 

 

 

Excel Extract what form : The trunk connects to the branch , use “\” Connection No .( After understanding the principle, you can write it in any other form you want )

give an example :

https\Tunnel to meaning \Tunnel( Tunnel ), Intermediate entities

https\Tunnel to meaning \ hide : The rules - Hide connection

 

Two , extract Xmind File branch content ( a key )

So how to analyze the above data structure ? use “from xmindparser import xmind_to_dict”, use xmindparser The package converts it into a dictionary format and processes it .

Another example :

 

 

This xmind File by xmind_to_dict It can be converted. Why ?

{'title': 'A', 'topics': [{'title': 'B1'}, {'title': 'B2', 'topics': [{'title': 'C1'}, {'title': 'C2'}]}, {'title': 'B3'}]}

Still not intuitive enough , use json The analyzer unfolds 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'
  }
]

 

Content in a list in , The outer layer of the dictionary title by “ canvas 1”,topic With what we need ( You can see that other places are called topics), This is a xmind It's not in the file , It turns out to be a fixed value , You can ignore . And then by taking list,A It's in the dictionary value value ,key by title, Its child nodes are installed in topics In the branch of . After processing, it's like this , The outermost layer is dict:

 

  So here comes the question , How to deal with it in the desired form ? Layer by layer key、value Do you ?

Of course not. , It's going to be a lot of work , And it's not good for reading and revising . Do you remember what I was thinking about ? Here we need to use what you think , you 're right , recursive .

Why recursion , Let's take a closer look at the structure :

A The three sub nodes of are respectively B1,B2,B3,B2 The child node of is C1C2, See the picture above. What do you think of ?

1, The title and child nodes are placed in different item in , namely topic Put the root node , that topics Then put its child nodes .

2,topics No child nodes ? image C1C2 That point has no child nodes , We found that , It doesn't either topics; meanwhile , There is no child node to prove that it is the last layer of this branch ; Just imagine , If A No child nodes , It's the only 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 any child nodes, then there are topics, If not, then not topics.

4,title Always pretend to be string, and topics It can hold list,list There's also dict, There can be no topics.

After four o'clock, I still feel confused ?

We need to take child nodes layer by layer to get what we want A\B2\C1、A\B2\C2, The node value is always in title in , But the child node is in the dict、list Inside dict in , And there's only one child node title, Yes, there is one title Add one more topics, This has already been said , Yes topics It also has its child nodes .

So it should be clear now ? It's not clear ? Let's do it again :

If Input Dictionary :

When the dictionary only has title when :

operation 1

When the dictionary has title and topics when :

operation 2

If Input list:

Traverse list Dictionary in :

Operate on each dictionary 3

If The input is neither a dictionary nor list:

Output value

 

 

The idea framework has been set up , That operation 1、2、3 What is it? ? In fact, it is the repeated operation of this framework , You can call yourself , This is, loosely, a popular explanation for recursion .

We post the 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 complete code ?

Unload the above conversion process 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 : recursive dictionary Files get easy to write Excel The form of form .
18  Be careful :rootstring Use both str To handle Chinese characters
19  @param root: take xmind After processing the dictionary file
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 ( minute )',
48 # ' Step description ',
49 # ' Expected results ',
50 # ' priority ',
51 # ' team ',
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 # ' team ': group,
68 # ' Way of execution ': runType,
69 # ' Use case types ':testcaseType,
70 # ' Test type ': testType,
71 # })

 

3、 ... and ,UI Interface

UI Interface tkinter 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 window icons 
 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 = (' Juvenility ',20)).pack()
 24
 25 # Create menu bar 
 26 MenuBar = tkinter.Menu(window)
 27 # Put the menu bar in the main window 
 28 window.config(menu=MenuBar)
 29 # Create file menu , Don't show windows 
 30 fileBar = tkinter.Menu(MenuBar, tearoff=0)
 31 # Add file menu item 
 32 fileBar.add_command(label=" instructions ")
 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 bar 
 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='\ Regular version use cases \ Current version name \ full name \ Demand name ')
 47 labe1 = tkinter.Label(window, text=' Use case path :').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=' open Xmind file ', 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 The 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 ( minute )',
120 ' Step description ',
121 ' Expected results ',
122 ' priority ',
123 ' team ',
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 ' team ': group,
143 ' Way of execution ': runType,
144 ' Use case types ': testcaseType,
145 ' Test type ': testType,
146  })
147
148 # Set up button Button acceptance function 
149 importbutton = tkinter.Button(window, text="2, Import Xmind file ", command=open_file)
150 importbutton.place(x=110,y=y + 9*step)
151 importbutton.configure(width =34,height=2)
152
153 # Set up 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 Repair :zhengyong731@pingan.com.cn",font = (' Song style ',8)).place(x=60,y=350)
159 # Tk().iconbitmap('D:\Code\Python\XmindToExcel\image\icon.ico')
160 window.mainloop()

Then there's another problem , What is the result of running ?

 

  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 Main file name .py

How to run the executable file with a black box ?

pyinstaller -F -w mycode.py (-w Just cancel the window )

3, Where is the generated executable file ?

In the master file sibling folder dist in ,

4, Specific file structure :

 

  Four , Statement

All the code is original , Because there's no tutorial available , Learn how hard it is to find a tutorial , So I'm going to throw a brick to attract jade , My level is limited , If there is something wrong with the article and the code , Please give me some advice , We can talk about it .

Welcome to reprint , Please indicate the following :

I am cnblogs Upper ID by puppet Lolo , The blog address is https://www.cnblogs.com/two-peanuts/ All blogs with original statement are my original works . The content of the blog is my independent research results except for the cited literature . Unless otherwise specified   Knowledge sharing A signature - Noncommercial use - Share in the same way 3.0 The Chinese mainland license agreement Licensing .

5、 ... and ,github Address

The specific file structure has been passed to github,github Address :https://github.com/ndnmonkey/transXmindToCSV , welcome star.

 

版权声明
本文为[Puppet Lolo]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database