Добавление скобок в регулярное выражение
Пишу код, который превращает строковое выражение в словарь (первая часть функций), все хорошо работает. И код, который превращает словарь в выражение. Все работает хорошо. Но тут встал вопрос о добавлении скобок "(", ")" в строковое представление выражения (например (a.b) * .c ), которые дополнительно задают приоритет. Как можно добавить в функцию tostring() скобки? (( изначально приоритет -- ‘*’ > ‘.’ > ‘|’))
regex = input("Enter stuff: ")
regex.replace(' ','') #getting rid of gaps
#we will create three functions with the priority we need
def parse_ast(string):
if '*' in string: #look, is there a "*" in our expression, if so, we return a dictionary of the form key == "*", and val which we slicing to "*"
return {'key' : '*', 'val' : string[:string.index('*')]}
else:
return {'key' : 'atm', 'val' : [string]}
def parse_dot(string):
if '.' in string:#look, is there a "." in our expression, if so,return dictionary wherein in val breaks a string using the "."
return {'key' : '.', 'val' : [parse_ast(j) for j in string.split('.')]}
else:
return parse_ast(string)#if not, then go straight to parsing asterisk
def main(string):
if '|' in string: #look, is there a "|" in our expression, if so,return dictionary wherein in val breaks a string using the "|"
return {'key' : '|', 'val' : [parse_dot(j) for j in string.split('|')]} # so we have a list of substrings
else:
return parse_dot(string) #if not, then go straight to parsing dot
special = ['|','.','*']
def tostring(dic): #function to derive an expression from our nested dictionary
if type(dic) == str: # we have 2 cases
return dic
if dic['key'] in special: # 1fst case: (if we were given a dictionary with a key in the form of an operation)
string = ""
if len(dic['val']) >= 1:# we just print differently if the number of operands is different)
string += tostring(dic['val'][0]) + dic['key']
if len(dic['val']) >= 2: # If number of operands is 1 then only 1st if, If 2 then the first 2, And if 3+ then all
string += tostring(dic['val'][1])
if len(dic['val']) >= 3:
for i in dic['val'][2:]:
string += dic['key'] + tostring(i)
return string
if dic['key'] == 'atm': # And if the key is an atom
return dic['val'][0]
return ""
x = main(regex)
print(x)
print(tostring(x))
Спасибо!
Например: У нас есть строка (a|b) * .c Она конвертируется в словарь: m = {'key': '|', 'val': [{'key': 'atm', 'val': ['a']}, {'key': '.', 'val': [{'key': '*', 'val': 'b'}, {'key': 'atm', 'val': ['c']}]}]} (это в коде сделано,работает) Вопрос: этот словарь нужно обратно перевести в (a|b) * . c