caratteri.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. # coding=utf8
  2. import sys
  3. from pprint import pprint
  4. mappa_caratteri = [
  5. "0", "1", "~", "2", "4", "+", "#", "3", "5", "6", "/", "7", "9", "-", "÷", "8",
  6. "Φ", "A", "δ", "B", "D", "=", "α", "C", "E", "F", "%", "G", "I", ",", "γ", "H",
  7. ".", "S", "θ", "T", "V", "!", ")", "U", "W", "X", "?", "Y", "\'", "&", "⊗", "Z",
  8. "ε", "J", "*", "K", "M", "(", "β", "L", "N", "O", "$", "η", "R", "P", "π", "Q"
  9. ]
  10. caratteri_python_a_elea = {
  11. char.decode('utf-8'): idx
  12. for idx, char in enumerate(mappa_caratteri) }
  13. def stringa_python_a_elea(string):
  14. s = []
  15. for i in string.decode('utf-8'):
  16. if i in (' ', '\n'):
  17. continue
  18. xx = caratteri_python_a_elea.get(i, None)
  19. if xx is None:
  20. raise Exception("carattere %s non mappato" % i)
  21. s.append(xx)
  22. return s
  23. def elea_a_c(l):
  24. l2 = ('%3d,' % i for i in l)
  25. return ' ' + ' '.join(l2)
  26. def stringa_elea_a_c(l):
  27. e = stringa_python_a_elea(l)
  28. e2 = elea_a_c(e)
  29. return e2 + " /* " + l + " */"
  30. PROLOGO = """#include "elea_tipi.h"
  31. const carattere %s[] = {
  32. """
  33. EPILOGO = """};
  34. const int %s_lunghezza = sizeof(%s) / sizeof(carattere);
  35. """
  36. def txt_to_c(stringa_txt, nome):
  37. x = []
  38. x += (PROLOGO % nome).splitlines()
  39. for line in stringa_txt.splitlines():
  40. l2 = line.strip()
  41. if len(l2) == 0: continue
  42. x.append(stringa_elea_a_c(l2))
  43. x += (EPILOGO % (nome, nome)).splitlines()
  44. return '\n'.join(x)
  45. def converti(nomefile):
  46. nome = nomefile.split('.', 1)[0]
  47. x = open(nomefile).read()
  48. c = txt_to_c(x, nome)
  49. open('%s.c' % nome, 'w').write(c)
  50. if __name__ == '__main__':
  51. try:
  52. nomefile = sys.argv[1]
  53. except:
  54. print "converte da txt in elea -> file c\n"
  55. print "usaggio: %s nomefile.txt"
  56. sys.exit()
  57. converti(nomefile)