我正在尝试以XML-格式(xmltv)搜索EPG (电子程序指南)。我想找到所有的节目,其中包含一个特定的文本,例如,哪些频道将显示一个特定的足球(足球)比赛今天。样本数据(实际数据为> 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>或desc属性包含特定文本(不区分大小写)时,我才想显示title属性。使用ElementTree,我尝试了这样的方法:
for title in root.findall("./programme/title"):
match = re.search(r'Santiago',title.text)
if match:
print(title.text)它将找到一个结果,但:
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[Ss]antiago不工作。发布于 2021-08-16 21:47:05
你不需要阅读正则表达式,试一试
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编辑:
要从每个programme获取所有数据,请尝试如下:
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支持。
https://stackoverflow.com/questions/68809117
复制相似问题