caratteri.py 1.9 KB

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