Я задаю переменной e
значение ['5+7']
, а i
0
e = ['5+7']
i = 0
Затем я делаю цикл и использую len(e)
while i != len(e):
И получаю вот такую ошибку:
TypeError: object of type 'NoneType' has no len()
Я использую PyCharm Community Edition (Python 3.8)
Если что, то ошибка в строке с while i != len(e):
Полный текст ошибки:
Traceback (most recent call last):
File "/sysroot/home/user/PycharmProjects/E/main.py", line 282, in <module>
compile_file("/sysroot/home/user/e/main.e") # Replace compile_file to ask_path and remove function argument
File "/sysroot/home/user/PycharmProjects/E/main.py", line 68, in compile_file
main(code)
File "/sysroot/home/user/PycharmProjects/E/main.py", line 215, in main
parser(lexer(code))
File "/sysroot/home/user/PycharmProjects/E/main.py", line 236, in lexer
solve(replac("\t", "", replac(" ", "", replac("}", "", replac("{", "", find(r"\{.*?\}", code))))))
File "/sysroot/home/user/PycharmProjects/E/main.py", line 79, in solve
while i != len(e):
TypeError: object of type 'NoneType' has no len()
Вот весь код: Ссылка на Google Диск
from sys import exit as stop
from os import system, name
from colorama import Fore
import re
variables = {}
def crit(pre, text, line = -1):
if line != -1:
print(f"{Fore.RED}[{pre}] Строка {line}: {text}{Fore.RESET}")
else:
print(f"{Fore.RED}[{pre}] {text}{Fore.RESET}")
stop()
def err(pre, text):
print(f"{Fore.RED}[{pre}] {text}{Fore.RESET}")
prefix = "E"
def find(pattern, text):
res = []
for match in re.finditer(pattern, text, re.S):
res.append(match.group())
return res
def to_repl(what, to, where):
i = len(what) - 1
while i != -1:
try:
where = where.replace(what[i], to)
except AttributeError:
to_repl(what[i], to, where)
i -= 1
return where
def replac(what, to, where):
i = len(where) - 1
while i != -1:
try:
where[i] = where[i].replace(what, to)
except AttributeError:
replac(what, to, where[i])
i -= 1
return where
def ask_path():
input("Введите путь к файлу: ").strip()
try:
f = open(path, 'r')
code = f.read()
f.close()
clear()
main(code)
except FileNotFoundError:
err(prefix, "Файл не найден")
ask_path()
except IsADirectoryError:
err(prefix, "Указан путь к директории")
ask_path()
def compile_file(path):
path = path.strip()
try:
f = open(path, 'r')
code = f.read()
f.close()
clear()
main(code)
except FileNotFoundError:
err(prefix, "Файл не найден")
ask_path()
except IsADirectoryError:
err(prefix, "Указан путь к директории")
ask_path()
def solve(e):
i = 0
print(e)
while i != len(e):
e = solve_num(e[i])
i += 1
def solve_num(num):
rounds = num.count('*') + num.count('/') + num.count('+') + num.count('-')
i = 0
# Lexer только для цифр. Тут же всё и будет решаться и это будет возращать готовое значение
# Если Lexer встречает умножение, или деление, то он выполняет это действие, изменяет num и алгоритм выполняется ещё раз
while rounds != 0:
num = solve_plus_minus(solve_mult_split(num))
rounds -= 1
def solve_mult_split(num):
mults = False
splts = False
num1 = ""
num2 = ""
stopped = False
pt = False
i = 0
while i != len(num) and not stopped:
if num[i] == '*':
mults = True
stopped = True
elif num[i] == '/':
splts = True
stopped = True
elif num[i] == '-' or num[i] == '+':
num1 = ""
else:
num1 += num[i]
i += 1
i = 0
stopped = False
while i != len(num) and not stopped:
if not pt:
if mults:
if num[i] == '*':
pt = True
elif splts:
if num[i] == '/':
pt = True
else:
if num[i] == '+' or num[i] == '-' or num[i] == '/' or num[i] == '*':
stopped = True
else:
num2 += num[i]
i += 1
print(f"[E] Умножение/деление: Число 1: {num1}. Число 2: {num2}")
if mults:
return num1 * num2
elif splts:
return num1 / num2
else:
return num
def solve_plus_minus(num):
pluss = False
minss = False
num1 = ""
num2 = ""
stopped = False
pt = False
i = 0
while i != len(num) and not stopped:
if num[i] == '+':
pluss = True
stopped = True
elif num[i] == '-':
minss = True
stopped = True
i += 1
i = 0
stopped = False
while i != len(num) and not stopped:
if not pt:
if pluss:
if num[i] == '+':
pt = True
elif minss:
if num[i] == '-':
pt = True
else:
if num[i] == '+' or num[i] == '-' or num[i] == '/' or num[i] == '*':
stopped = True
else:
num2 += num[i]
i += 1
print(f"[E] Сложение/вычитание: Число 1: {num1}. Число 2: {num2}")
if pluss:
return num1 + num2
elif minss:
return num1 - num2
else:
return num
def clear():
_ = system('cls' if name == 'nt' else 'clear')
def sub(ptrn, repl, arr):
i = len(arr) - 1
while i != -1:
try:
arr[i] = re.sub(ptrn, repl, arr[i])
except AttributeError:
sub(ptrn, repl, arr[i])
i -= 1
return arr
def fsplit(arr, spl):
i = len(arr) - 1
while i != -1:
try:
arr[i] = arr[i].split(spl)
except AttributeError:
fsplit(arr[i], spl)
i -= 1
return arr
def trim(arr):
i = len(arr) - 1
while i != -1:
try:
arr[i] = arr[i].strip()
except AttributeError:
trim(arr[i])
i -= 1
return arr
def main(code):
parser(lexer(code))
def cut(string):
return string.replace("'", "").replace('"', '').strip()
def parser(tokens):
z = 0
while len(tokens) > z:
if tokens[z][0] == "print":
print(tokens[z][1])
elif tokens[z][0] == "error":
crit(tokens[z][2], tokens[z][1])
elif tokens[z][0] == "clear":
clear()
elif tokens[z][0] == "var":
variables[tokens[z][1]] = tokens[z][2]
z += 1
def lexer(code):
code = to_repl(find(r">>.*?<<", code), "", code)
code = to_repl(find(r">.*?\n", code), "", code)
solve(replac("\t", "", replac(" ", "", replac("}", "", replac("{", "", find(r"\{.*?\}", code))))))
lin = 1
o = len(code.split("'")) - 1
d = len(code.split('"')) - 1
if o % 2 != 0:
crit(prefix, f"Непарное количество кавычек (' = {o})")
if d % 2 != 0:
crit(prefix, f'Непарное количество кавычек (" = {d})')
p = trim(fsplit(code.split("\n"), ":"))
r = []
i = 0
while i != len(p):
r.append([])
if p[i][0] == "print" or p[i][0] == "error" or p[i][0] == "clear" or p[i][0] == "var":
r[i].append(cut(p[i][0]))
if p[i][0] == "print":
args = trim(re.sub(r',(?=([^(\"|\')]*(\"|\')[^(\"|\')]*(\"|\'))*(?![^(\"|\')]*(\"|\')))', 'e_special_char_ᅠ0', p[i][1]).split("e_special_char_ᅠ0"))
if len(args) == 1:
r[i].append(cut(args[0]))
else:
crit(prefix, "Неправильное количество аргументов (ожидался 1 аргумент)", lin)
elif p[i][0] == "error":
args = trim(re.sub(r',(?=([^(\"|\')]*(\"|\')[^(\"|\')]*(\"|\'))*(?![^(\"|\')]*(\"|\')))', 'e_special_char_ᅠ0', p[i][1]).split("e_special_char_ᅠ0"))
if len(args) == 2:
r[i].append(cut(args[0]))
r[i].append(cut(args[1]))
else:
crit(prefix, "Неправильное количество аргументов (ожидалось 2 аргумента)", lin)
elif p[i][0] == "clear":
if trim(code.split("\n"))[i] != "clear":
crit(prefix, "Заданы аргументы (не ожидалось аргументов)")
elif p[i][0] == "var":
args = trim(re.sub(r',(?=([^(\"|\')]*(\"|\')[^(\"|\')]*(\"|\'))*(?![^(\"|\')]*(\"|\')))', 'e_special_char_ᅠ0', p[i][1]).split("e_special_char_ᅠ0"))
if len(args) == 2:
r[i].append(cut(args[0]))
r[i].append(cut(args[1]))
else:
crit(prefix, "Неправильное количество аргументов (ожидалось 2 аргумента)", lin)
lin += 1
elif p[i][0] == "":
lin += 1
else:
crit(prefix, f"Неизвестное кодовое слово: {p[i][0]}", lin)
i += 1
return list(filter(None, r))
compile_file("/sysroot/home/user/e/main.e") # Replace compile_file to ask_path and remove function argument
main.py
main.py. На экране.
while