【发布时间】:2018-09-17 12:37:44
【问题描述】:
我正在寻找使用 python 解析大型 xml 文件。该文件包含几个不同的元素。这是我正在处理的文件的示例:
<movie title="Searching">
<type>War, Thriller</type>
<format>DVD</format>
<year>2018</year>
<rating>PG</rating>
<stars>10</stars>
<description>Missing girl</description>
</movie>
<song title="Need You Now">
<type>Pop, Country</type>
<format>MP4</format>
<year>2010</year>
<singer>Lady Antebellum</rating>
<stars>8</stars>
</song>
<movie title="Sidewalk of New York">
<type>Romantic comedy</type>
<format>DVD</format>
<rating>PG</rating>
<stars>7</stars>
<description>Stories of people's perspective of love in NY</description>
</movie>
从上面的文件中,我想解析并存储与电影和歌曲元素相关的所有信息以列出。我正在使用 xml.sax 库,但遇到了如何区分元素的问题。例如,如果我解析类型、格式和年份标签,则无法区分它属于电影还是歌曲。这是我目前使用的一个 sn-p 代码:
import psycopg2
import xml.sax
from xml.sax.handler import ContentHandler
class MovieHandler( xml.sax.ContentHandler ):
def __init__(self):
self.CurrentData = ""
self.type = ""
self.format = ""
self.year = ""
self.data = {} #dict
self.list = [] #list to store information
self.list2 = []
self.list3 = []
self.list4 = []
self.list5 = []
# Call when an element starts
def startElement(self, tag, attributes):
self.CurrentData = tag
if tag == "movie":
title = attributes["title"]
self.list.append(title)
self.data['title'] = self.list
elif tag == "song":
title = attributes ["title"]
self.list2.append(title)
self.data['song_title'] = self.list2
# Call when an elements ends
def endElement(self, tag):
if self.CurrentData == "type":
type = self.type
self.list3.append(type)
self.data['type'] = self.list3
elif self.CurrentData == "format":
format = self.format
self.list4.append(format)
self.data['format'] = self.list4
elif self.CurrentData == "year":
year = int(self.year)
self.list5.append(year)
self.data['year'] = self.list5
self.CurrentData = ""
# Call when a character is read
def characters(self, content):
if self.CurrentData == "type":
self.type = content
elif self.CurrentData == "format":
self.format = content
elif self.CurrentData == "year":
self.year = content
上面代码的结果是类型、格式、年份都会被重复计算。这是输出示例:
{'format': ['DVD', 'MP4', 'DVD'],
'title': ['Searching', 'Need You Now', 'Sidewalk of New York'],
'type': ['War, Thriller',
'Pop, Country',
'Romantic Comedy'],
'year': [2018, 2010]}
关于如何解决这个问题的任何想法?谢谢!
【问题讨论】:
标签: python xml postgresql parsing xml-parsing