Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import re
- class File_Translator:
- def __init__(self, file):
- self.file = self.fopen(file)
- def fopen(self, file):
- with open(file, 'r') as f:
- return f.readlines()
- def tokenize(self, input_file):
- tokens = []
- file = input_file
- for line in file:
- line = line.split()
- for line in line:
- line = re.split(r'[^(a-zA-Z);]?[^%(a-z), a-zA-Z0-9;]?![{|}]', line)
- for result in line:
- tokens.append(result)
- return tokens
- def translate(self):
- code = self.tokenize(self.file)
- translation = []
- for index, token in enumerate(code):
- if token == 'int' and code[index + 1] == 'main()' and code[index + 2] == '{':
- translation.append('if __name__ == "main":\n')
- if token.startswith('for('):
- 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')
- if token.startswith('printf("'):
- if token[8] == '%' and token[9] in ('i', 'd', 'f', 'l', 'e'):
- translation.append(f'print({code[index + 1].replace(");", "")})\n')
- elif token[8] == '%' and token[9] in ('s', 'c'):
- translation.append(f'print("{code[index + 1].replace(");", "")})\n')
- elif token.startswith('printf("'):
- j = 0
- word = ''
- while True:
- try:
- if not code[index + j].endswith('");') or code[index + j].endswith(';' or None):
- if code[index + j] == '0;' and not code[index].endswith('");'):
- break
- word += f' {code[index + j].replace("printf", "print", 1)}'
- except:
- break
- j += 1
- translation.append(word.replace(word[-1], '', -1).replace(word[0], '', 0))
- return translation
- def main():
- translate = File_Translator('testing.c')
- translation = translate.translate()
- # print(translate.tokenize(translate.file))
- print(translation)
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment