【问题标题】:Python text to xml converting solutionsPython文本到xml转换解决方案
【发布时间】:2013-09-12 09:15:08
【问题描述】:

大家好,我已经用 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

感谢您的阅读,您能帮我解决这个问题吗?

【问题讨论】:

  • 我已尝试修复您的缩进,但不知道现在是否正确。如果是,那么最里面的if 将永远不会评估为true,因为包含Start 的行永远不会包含Duration,因此永远不会定义g。使用这样的输入数据,我会将这些行拆分为 Program 块,然后使用嵌套循环遍历每个块的行来迭代生成的块;然后您可以在内循环中收集数据并将其写入外循环,从而使结构更加清晰。

标签: python xml regex text


【解决方案1】:

从您的代码中我想说,这只是一个错字 - 您正在寻找 'duration',但该文件仅包含 'Duration',大写字母 D。因此,g 永远不会设置。您可以通过在开始时将变量设置为空字符串来初始化变量来避免这种行为。 附带说明一下,对于这样一个简单的任务,比如检查一行中不需要re 的单词,请尝试 - 我猜 - 更“pythonic”的方式:

if 'Duration' in line:
    #do something

【讨论】:

    猜你喜欢
    • 2011-06-04
    • 1970-01-01
    • 2013-05-20
    • 2020-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多