Skip to content

Instantly share code, notes, and snippets.

@piontas
Created October 8, 2014 23:41
Show Gist options
  • Save piontas/a24b4fefa68a96760250 to your computer and use it in GitHub Desktop.
Save piontas/a24b4fefa68a96760250 to your computer and use it in GitHub Desktop.
usage: ./program.py --xml ./data.txt or ./program.py --json ./data.txt
0: a:1, x:2, w:3
1: b:1, c:3, t:5
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import getopt
import json
from lxml import etree
class Program:
def __init__(self, file):
self.file_content = []
self.dict = {}
self.read_file(file)
def read_file(self, file):
with open(file) as f:
for line in f:
self.file_content.append(line.strip().replace(' ', ''))
def create_dict(self):
for line in self.file_content:
self.dict[int(line.split(':', 1)[0])] = {
dic.split(':')[0]: dic.split(':')[1] for dic in
(line.split(':', 1)[1]).split(',')}
def as_json(self):
return json.dumps(self.dict)
def as_xml(self):
root = etree.Element('program')
for m, d in self.dict.items():
minor = etree.Element('minor')
minor.set('nr', str(m))
for key, val in d.items():
child = etree.Element(key)
child.text = str(val)
minor.append(child)
root.append(minor)
return etree.tostring(root, pretty_print=True)
if __name__ == "__main__":
try:
opts, args = getopt.getopt(sys.argv[1:], "jx", ["json", "xml"])
if len(args) != 1:
print 'You have to specify file path!'
sys.exit(2)
except getopt.GetoptError as err:
print str(err)
sys.exit(2)
program = Program(args[0])
program.create_dict()
for o, v in opts:
if o in ('-j', '--json'):
print program.as_json()
if o in ('-x', '--xml'):
print program.as_xml()
@piontas
Copy link
Author

piontas commented Oct 8, 2014

./program.py --xml ./data.txt
./program.py --json ./data.txt
./program.py --json --xml ./data.txt

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment