Python не работает код не могу найти ошибку
Вот такой код:
import re
class Interpreter:
def __init__(self, filename):
self.file_name = filename
self.variables = {}
with open(filename) as code:
self.lines = len(code.readlines())
self.current_line = 1
def split_code(self, input_str):
pattern = r'\w+|\.|\=|<.*?>|\"w+"'
result = re.findall(pattern, input_str)
for i in range(len(result)):
try:
result[i] = int(result[i])
except ValueError:
pass
return result
def lex(self, c):
if c == []:
self.current_line += 1
elif c[0] == "out":
text = ""
for n in range(len(c)-1):
t = c[n]
if t[0:2] == "__":
try:
text += ''.join(self.variables[t[2:]])
except KeyError:
print(f"Ошибка. Перменная {t[2:]} отсутствует!")
else:
text += t
n += 1
text += ""
print(text)
elif c[0] == "new":
if c[1] in self.variables:
del self.variables[c[1]]
if c[1] == "int":
if c[4] == "inp":
zn = int(input(" ".join(c[5:])))
else:
zn = int(c[4])
self.variables[c[2]] = zn
elif c[1] == "string":
if c[4] == "inp":
zn = input(" ".join(c[5:]))
else:
zn = c[4]
self.variables[c[2]] = zn
def run(self):
with open(self.file_name, "r", encoding="utf-8") as code:
while self.current_line <= self.lines:
line = code.readline().replace("\n", "")
codeline = self.split_code(line)
self.lex(codeline)
self.current_line += 1
inter = Interpreter("programm.txt")
inter.run()
Код текстового файла:
new int x = inp Введи число
new string line = inp Вводи текст быстра
out __x __line
На вывод программа должна подавать, то что вводится в x
и line
Ответы (1 шт):
Автор решения: Сергей Ш
→ Ссылка
import re
class Interpreter:
def __init__(self, filename):
self.file_name = filename
self.variables = {}
with open(filename) as code:
self.txt_list = code.readlines()
self.lines = len(self.txt_list)
self.current_line = 1
def split_code(self, input_str):
...
def lex(self, c):
if not c:
self.current_line += 1
elif c[0] == "out":
text = ""
for t in c[1:]:
if t[0:2] == "__":
try:
text += str(self.variables[t[2:]])
except KeyError:
print(f"Ошибка. Перменная {t[2:]} отсутствует!")
print(text)
...
def run(self):
for code in self.txt_list:
line = code.replace("\n", "")
codeline = self.split_code(line)
self.lex(codeline)
self.current_line += 1
inter = Interpreter("programm.txt")
inter.run()
# веди число333
# води текст быстраddd
# 333ddd