大家好,我在 python 中编写了一些代码,它看起来像:
#! /usr/bin/env python
import re
output = open('epg.xml','w')
n = 0
print >> output, '<?xml version="1.0" encoding="utf-8" ?>'+'\t'
print >> output, '<data>'
with open('epg_slo_utf_xml.txt','r') as txt:
for line in txt:
if re.search('Program', line) !=None:
n =n + 1
e ='<program name=SLO>'+line+'</program>'
if re.search('Start', line) !=None:
n = n + 1
f ='<start>'+line+'</start>'
if re.search('duration', line) !=None:
n = n + 1
g ='<duration>'+line+'<duration>'
wo = e + f
print >> output, wo
print >> output , '</data>
但是当我想添加代码以从我的文本文件中发现 Duration 时,如下所示:
if re.search('duration', line) !=None:
n = n + 1
g ='<duration>'+line+'<duration>'
当我运行脚本时,我收到此错误消息:
Traceback (most recent call last):
File "./epg_transform.py", line 25, in <module>
wo = e + f + g
NameError: name 'g' is not defined
我的文本文件如下所示:
Program 5
Start 2013-09-12 05:30:00
Duration 06:15:00
Title INFOCANALE
Program 6
Start 2013-09-12 06:40:00
Duration 00:50:00
Title Vihar
Program 9
Start 2013-09-12 06:45:00
Duration 00:29:00
Title TV prodaja
Program 7
Program 6
Program 13
Start 2013-09-12 06:20:00
Duration 00:50:00
Title Kursadžije
我认为问题是当 re.search 找到 Program 但在文本文件中没有其他元素时,或者可能是具有多重播放开始、持续时间、标题的 Program,例如:
Program 7
Start 2013-09-16 00:10:00
Duration 02:00:00
Title Love TV
Start 2013-09-16 02:10:00
Duration 01:50:00
Title Nočna ptica
感谢阅读,您能帮我解决这个问题吗?