前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >将xml文件转为txt文件

将xml文件转为txt文件

作者头像
hankleo
发布2020-09-17 10:22:38
发布2020-09-17 10:22:38
2.8K00
代码可运行
举报
文章被收录于专栏:Hank’s BlogHank’s Blog
运行总次数:0
代码可运行
代码语言:javascript
代码运行次数:0
运行
复制
import os
import re
import sys
import glob
import xml.etree.ElementTree as ET

def xml_to_txt(indir,outdir):

    os.chdir(indir)
    annotations = os.listdir('.')
    annotations = glob.glob(str(annotations)+'*.xml')
    pat = re.compile('(?<=\>).*?(?=\<)')

    for i, file in enumerate(annotations):
        file_save = file.split('.')[0]+'.txt'
        file_txt=os.path.join(outdir,file_save)
        f_w = open(file_txt,'w',encoding="utf-8")

        tree=ET.parse(file)
        root = tree.getroot()

        for obj in root.iter('PostItem'):
                current = list()
                for ele in obj.iter():
                    if "content" in ele.tag:
                        content = obj.find('content').text
                        if content:
                            content = re.sub(r'</?\w+[^>]*>','',content).replace("&nbsp;"," ").strip()
                            print(content)
                            f_w.write(content)
                            f_w.write("\n")
                    if "caption" in ele.tag:
                        caption = obj.find('caption').text
                        if caption:
                            caption = re.sub(r'</?\w+[^>]*>','',caption).replace("&nbsp;"," ").strip()
                            f_w.write(caption)
                            f_w.write("\n")
                            print(caption)

indir='E:\Data\demo-xml' #打开目录
outdir='E:\Data\demo-txt' #保存目录

xml_to_txt(indir,outdir)
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-10-23 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档