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=' ')

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>

python解析XML,提取标签内容

重庆:云蒸霞蔚山村美 朝霞白云入画来

相关推荐