drunkpolishbear

My head hurt

Jan 7th, 2020
604
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.39 KB | None | 0 0
  1. import re
  2.  
  3. class File_Translator:
  4.     def __init__(self, file):
  5.         self.file = self.fopen(file)
  6.  
  7.     def fopen(self, file):
  8.         with open(file, 'r') as f:
  9.             return f.readlines()
  10.  
  11.     def tokenize(self, input_file):
  12.         tokens = []
  13.         file = input_file
  14.         for line in file:
  15.             line = line.split()
  16.             for line in line:
  17.                 line = re.split(r'[^(a-zA-Z);]?[^%(a-z), a-zA-Z0-9;]?![{|}]', line)
  18.                 for result in line:
  19.                     tokens.append(result)
  20.  
  21.         return tokens
  22.  
  23.     def translate(self):
  24.         code = self.tokenize(self.file)
  25.         translation = []
  26.         for index, token in enumerate(code):
  27.             if token == 'int' and code[index + 1] == 'main()' and code[index + 2] == '{':
  28.                 translation.append('if __name__ == "main":\n')
  29.  
  30.             if token.startswith('for('):
  31.                 translation.append(f'for {code[index + 1]} in range({code[index + 3].replace(code[index + 3][-1], "", index + 3)}, {code[index + 6].replace(code[index + 6][-1], "", index + 6)}):\n')
  32.  
  33.             if token.startswith('printf("'):
  34.                 if token[8] == '%' and token[9] in ('i', 'd', 'f', 'l', 'e'):
  35.                     translation.append(f'print({code[index + 1].replace(");", "")})\n')
  36.  
  37.                 elif token[8] == '%' and token[9] in ('s', 'c'):
  38.                     translation.append(f'print("{code[index + 1].replace(");", "")})\n')
  39.  
  40.                 elif token.startswith('printf("'):
  41.                     j = 0
  42.                     word = ''
  43.                     while True:
  44.                         try:
  45.                             if not code[index + j].endswith('");') or code[index + j].endswith(';' or None):
  46.                                 if code[index + j] == '0;' and not code[index].endswith('");'):
  47.                                     break
  48.                                 word += f' {code[index + j].replace("printf", "print", 1)}'
  49.                         except:
  50.                             break
  51.                         j += 1
  52.                     translation.append(word.replace(word[-1], '', -1).replace(word[0], '', 0))
  53.  
  54.         return translation
  55.  
  56.  
  57. def main():
  58.     translate = File_Translator('testing.c')
  59.     translation = translate.translate()
  60.     # print(translate.tokenize(translate.file))
  61.     print(translation)
  62.  
  63. if __name__ == '__main__':
  64.     main()
Advertisement
Add Comment
Please, Sign In to add comment