elea9003-emu/caratteri.py

81 lines
1.8 KiB
Python
Raw Normal View History

# coding=utf8
import sys
from pprint import pprint
mappa_caratteri = [
"0", "1", "~", "2", "4", "+", "#", "3", "5", "6", "/", "7", "9", "-", "÷", "8",
"Φ", "A", "δ", "B", "D", "=", "α", "C", "E", "F", "%", "G", "I", ",", "γ", "H",
".", "S", "θ", "T", "V", "!", ")", "U", "W", "X", "?", "Y", "\'", "&", "", "Z",
"ε", "J", "*", "K", "M", "(", "β", "L", "N", "O", "$", "η", "R", "P", "π", "Q"
]
caratteri_python_a_elea = {
char.decode('utf-8'): idx
for idx, char in enumerate(mappa_caratteri) }
def stringa_python_a_elea(string):
s = []
for i in string.decode('utf-8'):
if i in (' ', '\n'):
continue
xx = caratteri_python_a_elea.get(i, None)
if xx is None:
raise Exception("carattere %s non mappato" % i)
s.append(xx)
return s
def elea_a_c(l):
l2 = ('%3d,' % i for i in l)
return ' ' + ' '.join(l2)
def stringa_elea_a_c(l):
e = stringa_python_a_elea(l)
e2 = elea_a_c(e)
return e2 + " /* " + l + " */"
PROLOGO = """#include "elea_tipi.h"
const carattere %s[] = {
"""
EPILOGO = """};
const int %s_lunghezza = sizeof(%s) / sizeof(carattere);
"""
def txt_to_c(stringa_txt, nome):
x = []
x += (PROLOGO % nome).splitlines()
for line in stringa_txt.splitlines():
l2 = line.strip()
if len(l2) == 0: continue
x.append(stringa_elea_a_c(l2))
x += (EPILOGO % (nome, nome)).splitlines()
return '\n'.join(x)
def converti(nomefile):
nome = nomefile.split('.', 1)[0]
x = open(nomefile).read()
c = txt_to_c(x, nome)
open('%s.c' % nome, 'w').write(c)
if __name__ == '__main__':
try:
nomefile = sys.argv[1]
except:
print "converte da txt in elea -> file c\n"
print "usaggio: %s nomefile.txt"
sys.exit()
converti(nomefile)