python解析XML,提取標籤內容
阿新 • • 發佈:2018-12-17
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>