#!python3importreimportxml.etree.ElementTreeasETrex=re.compile(r'''(?P
Longitude|Latitude|date&time|gsm\s+cell\s+id|Neighboring\s+List-\s+Lac\s+:\s+Cid\s+:\s+RSSI)\s*:?\s*(?P.*)''',re.VERBOSE)root=ET.Element('root')root.text='\n'# newline before the celldata elementwithopen('cell.txt')asf:celldata=ET.SubElement(root,'celldata')celldata.text='\n'# newline before the collected elementcelldata.tail='\n\n'# empty line after the celldata elementstatus=0# init status of the finite automatonforlineinf:ifstatus==0:# lines of the heading expected# If the line contains the wanted data, process it.m=rex.search(line)ifm:# Fix some problems with the title as it will be used# as the tag name.title=m.group('title')title=title.replace('&','')title=title.replace(' ','')ifline.startswith('Neighboring'):neighbours=ET.SubElement(celldata,'neighbours')neighbours.text='\n'neighbours.tail='\n'status=1# empty line and then list of neighbours expectedelse:e=ET.SubElement(celldata,title.lower())e.text=m.group('value')e.tail='\n'# keep the same statuselifstatus==1:# empty line expectedifline.isspace():status=2# list of neighbours must followelse:raiseRuntimeError('Empty line expected. (status == {})'.format(status))status=999# error statuselifstatus==2:# neighbour or the empty line as final separatorifline.isspace():celldata=ET.SubElement(root,'celldata')celldata.text='\n'celldata.tail='\n\n'status=0# go to the initial statuselse:# This is the neighbour item. Split it by colon,# and set the attributes of the item element.item=ET.SubElement(neighbours,'item')item.tail='\n'lac,cid,rssi=(a.strip()forainline.split(':'))item.attrib['lac']=lacitem.attrib['cid']=ciditem.attrib['rssi']=rssi.split()[0]# dBm removed# keep the same statuselifstatus==999:# error status -- break the loopbreakelse:raiseLogicError('Unexpected status {}.'.format(status))break# Display for debuggingET.dump(root)# Include the root element to the tree and write the tree# to the file.tree=ET.ElementTree(root)tree.write('cell.xml',encoding='utf-8',xml_declaration=True)用python将xml文件转换为txt文件_如何使用python将.txt文件转换为xml文件?
最新推荐文章于 2024-04-12 22:45:00 发布