File: iso2tab.py

package info (click to toggle)
iso-codes 0.44-1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 17,620 kB
  • ctags: 47
  • sloc: xml: 13,041; ansic: 240; sh: 234; perl: 216; python: 171; makefile: 133
file content (82 lines) | stat: -rwxr-xr-x 1,866 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#!/usr/bin/python
#
# Read iso-codes data file and output a .tab file
# 
# Copyright (C) 2004 Alastair McKinstry <mckinstry@debian.org>
# Released under the GPL.
# $Id: iso2tab.py,v 1.1 2004/05/16 20:20:42 mckinstry Exp $

from xml.sax import saxutils, make_parser, saxlib, saxexts, ContentHandler
from xml.sax.handler import feature_namespaces
import sys, os, getopt, urllib2

class printLines(saxutils.DefaultHandler):
    def __init__(self,element, nameslist, ofile):
         """ 
	 nameslist is the elements to be printed in  strings,
	 """
         self.attrnames = nameslist
	 self.element = element
	 self.ofile = ofile

    def startElement(self, name, attrs):
        # Get the name attributes
	if name != self.element:
	    return
	s = ""
	for aname in self.attrnames:
		n = attrs.get(aname, None)
		if n != None:
			if type(n) == unicode:
			    n = n.encode('UTF-8')
			if s == "":
			    s = n
			else:
			    s = s + '\t' + n
	ofile.write(s + "\n")


## 
## MAIN
##

try:
    (opts,trail)=getopt.getopt(sys.argv[1:],"e:f:", ["element=", "fields="])
    assert trail, "No argument provided"
except Exception,e:
    print "ERROR: %s" % e
    print
    print "Usage: iso2pot filename [outfilename]"
    print " filename: xml data file from iso-codes package"
    print " outfilename: Write to this file"
    sys.exit(1)

fields = ["name","official_name"]

for opt, arg in opts:
    if opt in ('--element'):
        element = arg
    elif opt in ('-f', '--fields'):
    	fields = arg.split(',')

if len(trail)==2:
    ofile = open(trail[1], 'w')
else:
    ofile = sys.stdout

p = make_parser()
p.setErrorHandler(saxutils.ErrorPrinter())

try:
    dh = printLines(element, fields, ofile)
    p.setContentHandler(dh)
    p.parse(trail[0])
except IOError,e:
    print in_sysID+": "+str(e)
except saxlib.SAXException,e:
    print str(e)


ofile.close()