使用正则表达式解析xml文件:期望的字符串或缓冲区

时间:2015-09-25 07:34:48

标签: python regex xml xml-parsing

我正在尝试使用正则表达式从xml文件中获取一些数据(我知道我应该使用一些xml解析器,但如果你之前没有使用过任何xml解析器,那么正则表达式似乎更简单)

这是我的python代码:

import datetime,re
date= datetime.datetime.today().strftime('%Y%m%d')

output = open(r'C:\Users\Peter\AppData\Roaming\Kodi\addons\plugin.video.videoaddon\resources\epg.xml', 'r')
match = re.compile('start="%s(.+?)\s.+?".+?channel="Bravo (US)"\s><title>(.+?)</title>'%(date)).findall(output)
for start,title in match:
    print(start,title)

我得到TypeError: Expected string or buffer

有谁可以解释为什么我会收到此错误?

如果有人有兴趣,请提供我想要做的其他信息:

XML文件示例:http://pastebin.com/9yC1FTYu 我知道这个xml格式不好,但我就是从软件API中获取它的。

基本上我需要得到: start时间戳的最后一部分,第一部分必须与日期匹配,<title>文本。我需要在channel匹配Bravo (US)的情况下获取这些内容。

2 个答案:

答案 0 :(得分:1)

您正在将文件对象传递给pattern.findall()方法。您必须首先读取文件:

pattern = re.compile('start="%s(.+?)\s.+?".+?channel="Bravo (US)"\s><title>(.+?)</title>'%(date))
filename = r'C:\Users\Peter\AppData\Roaming\Kodi\addons\plugin.video.videoaddon\resources\epg.xml'
with open(filename, 'r') as xmlfile:
    match = pattern.findall(output.read())

但是,您应该在这里使用XML解析器。标准库附带ElementTree API

import xml.etree.ElementTree as ET

filename = r'C:\Users\Peter\AppData\Roaming\Kodi\addons\plugin.video.videoaddon\resources\epg.xml'
tree = ET.parse(filename)
for programme in tree.findall(".//programme[@channel='Bravo (US)']"):
    showtime = programme.attrib['start']
    if showtime.startswith(date):
        print showtime[8:14], programme.find('title').text

如果您安装了lxml,则可以使用更复杂的XPath查询,包括搜索日期的查询:

import lxml.etree as ET

filename = r'C:\Users\Peter\AppData\Roaming\Kodi\addons\plugin.video.videoaddon\resources\epg.xml'
date_predicate = '[starts-with(@start, "{}")]'.format(date)
tree = ET.parse(filename)
for programme in tree.xpath('.//programme[@channel="Bravo (US)"]' + date_predicate):
    showtime = programme.attrib['start']
    print showtime[8:14], programme.find('title').text

答案 1 :(得分:0)

您需要使用read()或其他方式读取文件,文件对象仅存储在输出变量而不是内容中。

output = open(r'C:\Users\Peter\AppData\Roaming\Kodi\addons\plugin.video.videoaddon\resources\epg.xml', 'r').read()
                                                                                                              ^