caratteri.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 : idx
  12. for idx, char in enumerate(mappa_caratteri) }
  13. def stringa_python_a_elea(string):
  14. s = []
  15. for i in string:
  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 = """/* Questo file e` generato automaticamente a partire
  31. * dai sorgenti testuali (file .elea-txt).
  32. * Non modificare!
  33. */
  34. #include "elea_tipi.h"
  35. const carattere %s[] = {
  36. """
  37. EPILOGO = """};
  38. const int %s_lunghezza = sizeof(%s) / sizeof(carattere);
  39. """
  40. def txt_to_c(stringa_txt, nome):
  41. x = []
  42. x += (PROLOGO % nome).splitlines()
  43. for line in stringa_txt.splitlines():
  44. l2 = line.strip()
  45. if len(l2) == 0: continue
  46. x.append(stringa_elea_a_c(l2))
  47. x += (EPILOGO % (nome, nome)).splitlines()
  48. return '\n'.join(x)
  49. def converti(nomefile):
  50. nome = nomefile.split('.', 1)[0]
  51. x = open(nomefile).read()
  52. c = txt_to_c(x, nome)
  53. open('%s.c' % nome, 'w').write(c)
  54. if __name__ == '__main__':
  55. try:
  56. nomefile = sys.argv[1]
  57. except:
  58. print ("converte da txt in elea -> file c\n")
  59. print ("usaggio: %s nomefile.txt")
  60. sys.exit()
  61. converti(nomefile)