python - 尝试搜索 EPG XML 数据

标签 python xml elementtree epg

我正在尝试搜索 XML 格式 ( xmltv ) 的 EPG(电子节目指南)。我想找到所有包含特定文本的节目,例如今天哪些 channel 将播放特定的足球(足球)比赛。 示例数据(真实数据是 > 20000 个元素):

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE tv SYSTEM "xmltv.dtd">
<tv generator-info-name="TX" generator-info-url="http://epg.net:8000/">
<channel id="GaliTV.es">
    <display-name>GaliTV</display-name>
    <icon src="http://logo.com/logos/GaliTV.png"/>
</channel>
<programme start="20210814080000 +0200" stop="20210814085500 +0200" channel="GaliciaTV.es" >
        <title>A Catedral de Santiago e o Mestre Mateo</title>
        <desc>Serie de catedral de Santiago de Compostela.</desc>
    </programme>
    <programme start="20210815050000 +0200" stop="20210815055500 +0200" channel="GaliciaTV.es" >
        <title>santiago</title>
        <desc>Chili.</desc>
    </programme>
</tv>

我想显示 <programme>属性仅当 titledesc属性包含特定文本(不区分大小写)。使用 ElementTree ,我试过这个:

for title in root.findall("./programme/title"):
   match = re.search(r'Santiago',title.text)
   if match:
       print(title.text)

它会找到一个结果,但是:

  1. 我收到一个我不明白的错误:
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "/usr/lib/python2.7/re.py", line 146, in search
    return _compile(pattern, flags).search(string)
TypeError: expected string or buffer
  1. 我不知道如何搜索不区分大小写,[Ss]antiago不起作用。
  2. 我想从父元素返回结果(例如 programme.attributes )。

最佳答案

你不会为此阅读正则表达式;尝试

for title in doc.findall('.//programme//title'):
    if "santiago" in title.text.lower():
        print(title.text)

你的样本的输出应该是

A Catedral de Santiago e o Mestre Mateo
santiago

编辑:

要从每个程序中获取所有数据,试试这个:

for prog in doc.findall('.//programme'):
    title = prog.find('title').text
    if "santiago" in title.lower():      
        start,stop,channel = prog.attrib.values()
        desc = prog.find('.//desc').text
        print(start,stop,channel,'\n',title,'\n',desc)
        print('-----------')

输出:

20210814080000 +0200 20210814085500 +0200 GaliciaTV.es 
 A Catedral de Santiago e o Mestre Mateo 
 Chili.
-----------
20210815050000 +0200 20210815055500 +0200 GaliciaTV.es 
 santiago 
 Chili.

我还要补充一点,如果 xml 变得有点复杂,从 ElementTree 切换到 lxml 可能是个好主意,因为后者有更好的 xpath 支持。

关于python - 尝试搜索 EPG XML 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68809117/

相关文章:

python - 检查键是否在字典中且值不为 None 的最 Pythonic 方法

python - 在Python中用正则表达式替换模式的一部分

.net - 在 .NET 中将二进制 XML 读取为文本

xml - 如何区分两个 .xml 文件并在 XSLT 中存储差异?

python - 在 python 中编写修改后的 XML 元素

python - 如何使用python解析XML到所需的自定义字段

python - python的xml.etree.ElementTree支持DTD吗?

Python比较md5哈希

python - 如何使用 Python 通过 App Function 向 Azure 存储表插入数千行

xml - 针对 XSD 验证 XML 时出错