ementTree(root)
tree.write('oooo.xml',encoding='utf-8', short_empty_elements=False)
方式三
from xml.etree import ElementTree as ET
# 创建根节点
root = ET.Element("famliy")
# 创建节点大儿子
son1 = ET.SubElement(root, "son", attrib={'name': '儿1'})
# 创建小儿子
son2 = ET.SubElement(root, "son", attrib={"name": "儿2"})
# 在大儿子中创建一个孙子
grandson1 = ET.SubElement(son1, "age", attrib={'name': '儿11'})
grandson1.text = '孙子'
et = ET.ElementTree(root) #生成文档对象
et.write("test.xml", encoding="utf-8", xml_declaration=True, short_empty_elements=False)
名称规范档文本
名称规范档没有提供批量下载同一人物的接口,在数据量大的实验需求中,设计实现了处理批量文本的方法。
首先,在下载的同一文档中包含不同ID号的多条人物数据,分别以 开头,以结尾,因此第一步,逐行读取文本,匹配结尾标识符“\n”,匹配成功则将先前读取的xml文档写出到新的文件,并给与新的命名以区别不同文本,实现代码如下:
def file_seperate(file_path,to_path):
for fileName in os.listdir(file_path):
f1 = open(file_path+"/"+fileName,'r',encoding="utf-8")
# print(file_path+"/"+fileName)
text = ""
num = 1
for content in f1.readlines():
text += content
if "</collection>"+"\n" == content:
num_str = str(num)
f2 = open(to_path + "/0" + num_str + fileName ,'w',encoding="utf-8")
f2.write(text)
f2.close()
text = ""
num = num + 1
f1.close()
解析结果可得(以沈从文为例)01沈从文.xml、02沈从文.xml、03沈从文.xml,进一步分析,在每一篇XML文件,要获取具体属性值构建目标文本集,为进一步的数据处理提供依据。根据研究需要,获取xml文件中的collection>>record>>datafield>>subfield字段,并限定具体属性的subfield字段,如{'code': 'a'}、{'code': 'f'}、 {'code': '3'}、{'code': 'u'},循环读取进行匹配,匹配成功则构建新的目标文本,与原文本同名。实现代码如下:
def xml_parse(file_path,Target_path):
for fileName in os.listdir(file_path):
file = file_path+"/"+fileName
text = ''
tree = ET.parse(file)
root = tree.getroot()
for node in root:
for node_node in node:
if node_node.attrib == {'tag': '200', 'ind1': ' ', 'ind2': '0'} or node_node.attrib =={'tag': '400', 'ind1': ' ', 'ind2': '0'} or node_node.attrib =={'tag': '810', 'ind1': ' ', 'ind2': ' '} or node_node.attrib =={'tag': '830', 'ind1': ' ', 'ind2': ' '} or node_node.attrib =={'tag': '856', 'ind1': '4', 'ind2': ' '}:
for subfield in node_node:
if subfield.attrib == {'code': 'a'} or subfield.attrib == {'code': 'f'} or subfield.attrib == {'code': '3'} or subfield.attrib == {'code': 'u'}:
text = text + subfield.text
print(text)
f = open(Target_path+"/"+fileName,'w',encoding='utf-8')
f.write(text)
f.close()
主函数如下,分别设定原始路径,处理文件路径,目标文件路径:
if __name__ == "__main__":
path_Source = "D:/study/name_cluster/test/test02/data-Source"
path_Separate = "D:/study/name_cluster/test/test02/data-Separate"
path_Target = "D:/study/name_cluster/test/test02/data-Target"
file_seperate(path_Source,path_Separate)
xml_parse(path_Separate,path_Target)