I wanted to create test data easily, so I created a large amount of test data creation tools in python. Specifically, the file name and file contents are stored in tsv, read this, rewrite only the target tag of the xml template, and output the test xml file in a batch.
FILENAME SENTENCE
sample_1.xml ice cream
sample_2.xml chocolate box
sample_3.xml candy bar
<root>
<Text>sweets</Text>
<originalText>sweets</originalText>
<head>sweets</head>
</root>
3.exportToXML.py
#!/usr/bin/env python
import csv
import xml.etree.ElementTree as ET
import shutil
import os
import glob
#Initialize output folder
for file in glob.glob('C:\\tools\\output\\*.xml', recursive=True):
os.remove(file)
#Get variable declaration file name and rewrite word
#file name
fName = ""
#And the word of rewriting
fDoc = ""
#Open the input tsv file
tsv_file = open(r"C:\\tools\sample.tsv", "r", encoding="utf-8", errors="", newline="" )
#Parse the file with a reader
f = csv.reader(tsv_file, delimiter="\t", doublequote=True, lineterminator="\n", quotechar='"', skipinitialspace=True)
data = [ v for v in f]
for i in range(len(data)):
#Do not read header
if i > 0:
fName = (data[i][0])
fDoc = (data[i][1])
fPath = 'C:\\tools\\output\\' + fName
#Copy the template.
shutil.copy('C:\\tools\\templete.xml',fPath)
tree = ET.parse(fPath)
root = tree.getroot()
for name in root.iter('text'):
name.text = fDoc
print(name.text)
for hname in root.iter('head'):
hname.text = fName
tree.write(fPath, encoding='UTF-8')
C: \ tools
and create a ʻoutput` folder under it.
Please execute the source of 3 in the python execution environment. The environment creation / execution method is summarized here. ■ Python (anaconda) development environment construction procedure (SpringToolsSuites) _2020.6 point
As shown in the list of tsv files, I was able to change the contents of the template and output the files in a batch.
that's all.
Recommended Posts