用python将xml文件转换为txt文件_如何使用python将.txt文件转换为xml文件?

#!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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值