0

こんにちは皆さん、私は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

読んでくれてありがとう。この問題を解決してくれませんか?

4

1 に答える 1