python解析XML,提取标签内容

import xml.dom.minidom as xmldom
import os

xml_filepath = os.path.abspath("./originalData/train.xml")
# xml_filepath=os.path.abspath("V5-13.xml")
# 得到文件对象
dom_obj = xmldom.parse(xml_filepath)

# 得到元素对象
element_obj = dom_obj.documentElement

# 获得子标签

sub_element_obj = element_obj.getElementsByTagName("weibo")

for i in range(len(sub_element_obj)):
    if sub_element_obj[i].getAttribute("emotion-type1") != "none":
        sub_element_obj1 = sub_element_obj[i].getElementsByTagName("sentence")
        for j in range(len(sub_element_obj1)):
            if sub_element_obj1[j].getAttribute("opinionated") == "Y":
                print(sub_element_obj1[j].getAttribute("emotion-1-type"), end='\t')
                print(sub_element_obj1[j].firstChild.data, end='')
                print()


所对应的XML格式

<weibo id="1" emotion-type="none">
    <sentence id="1" emotion_tag="N">三八节下午路过中牟县~见到很多美女~手执鲜花[鲜花]~一打听~这里不仅美女如云~而且是千古笫一帅哥潘安的故里。。。</sentence>
    <sentence id="2" emotion_tag="N">[给力][萌]</sentence>
  </weibo>
  <weibo id="2" emotion-type="sadness">
    <sentence id="1" emotion_tag="Y" emotion-1-type="like" emotion-2-type="none">源海都学愤怒鸟的声音,好像好厉害…</sentence>
    <sentence id="2" emotion_tag="Y" emotion-1-type="sadness" emotion-2-type="none">还比愤怒鸟射击的动作,我为啥一千啊现在…</sentence>
    <sentence id="3" emotion_tag="Y" emotion-1-type="sadness" emotion-2-type="anger">海赫还悄悄话了刚才,怎么不是我四千二的时候啊哈哈,悲愤!</sentence>
  </weibo>

 

  • 8
    点赞
  • 47
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值