解析嵌套表达式以检索每个内部函数

2024-03-28 17:38:53 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个表达式,如下所示:

expression = "LEN(Replace(Lower(UPPER([ProductName]+[ProductName])), 'chaichai', 'chai'))"

所需输出:

['UPPER([ProductName]+[ProductName])','Lower(UPPER([ProductName]+[ProductName]))','Replace(Lower(UPPER([ProductName]+[ProductName])),'chaichai','chai')','LEN(Replace(Lower(UPPER([ProductName]+[ProductName])),'chaichai','chai'))']

我已尝试以下代码,但未获得所需结果:

exp_splits = expression.strip(')').split('(')
for i_enm, i in enumerate(range(len(exp_splits)-2, -1, -1), start=1):
     result.append(f"{'('.join(exp_splits[i:])}{')'*i_enm}")
print(result)

我的代码的输出:

["UPPER([ProductName]+[ProductName])),'chaichai','chai')", "Lower(UPPER([ProductName]+[ProductName])),'chaichai','chai'))", "Replace(Lower(UPPER([ProductName]+[ProductName])),'chaichai','chai')))", "LEN(Replace(Lower(UPPER([ProductName]+[ProductName])),'chaichai','chai'))))"]

Tags: 代码len表达式resultupperlowerreplacesplit
2条回答
import re

e = "LEN(Replace(Lower(UPPER([ProductName]+[ProductName])),'chaichai','chai'))"

print ([e[i:j+1] for i in range(len(e)) for j in range(len(e)) if e[i:j+1].count('(') == e[i:j+1].count(')') != 0 and (e[i-1] == '(' or i == 0) and e[j] == ')'])

输出:

["LEN(Replace(Lower(UPPER([ProductName]+[ProductName])),'chaichai','chai'))", "Replace(Lower(UPPER([ProductName]+[ProductName])),'chaichai','chai')", 'Lower(UPPER([ProductName]+[ProductName]))', 'UPPER([ProductName]+[ProductName])']

展开的版本:

for i in range(len(e)):
    for j in range(len(e)):
        #Check for same number of opening/closing parenthesis
        if e[i:j+1].count('(') == e[i:j+1].count(')') != 0:
            #Check that (first char is preceded by an opening parenthesis OR that first char is the beginning of e) AND last char is a parenthesis
            if (e[i-1] == '(' or i == 0) and e[j] == ')':
                print (e[i:j+1])

输出:

LEN(Replace(Lower(UPPER([ProductName]+[ProductName])),'chaichai','chai'))
Replace(Lower(UPPER([ProductName]+[ProductName])),'chaichai','chai')
Lower(UPPER([ProductName]+[ProductName]))
UPPER([ProductName]+[ProductName])

使用拆分和for循环的方法

这里有另一种方法来实现这一点。在这种方法中,我将字符串拆分为多个部分。 用左括号和右括号将它们分开。 然后每次连接它们以创建表达式

假设:表达式的左括号和右括号数量相等

  • 步骤1:计算字符串中左括号的数目
  • 步骤2:用左括号拆分表达式
  • 步骤3:从左括号列表中弹出最后一个表达式,然后 存储到正确的表达式中。这包含右括号
  • 步骤4:用右括号拆分表达式
  • 第五步:既然两边都有了,就把它们缝在一起
  • 注意:连接表达式时,左侧从右侧开始 到左边(索引-1到0),右边从左到右 (索引0到-1)
  • 注意:对于每个迭代,您需要连接上一个答案 左右

代码如下所示:

expression = "LEN(Replace(Lower(UPPER([ProductName]+[ProductName])),'chaichai','chai'))"

n = expression.count('(')

exp_left = expression.split('(')
exp_right = exp_left.pop().split(')')
    
exp_list = []

exp_string = ''

for i in range(n):
    exp_string = exp_left[-i-1] + '(' + exp_string + exp_right[i] + ')'
    exp_list.append(exp_string)

for exp in exp_list: print (exp)

其输出将为:

UPPER([ProductName]+[ProductName])
Lower(UPPER([ProductName]+[ProductName]))
Replace(Lower(UPPER([ProductName]+[ProductName])),'chaichai','chai')
LEN(Replace(Lower(UPPER([ProductName]+[ProductName])),'chaichai','chai'))

下面的代码与上面的代码相同。我在每一行都添加了注释,以便您了解正在进行的操作

expression = "LEN(Replace(Lower(UPPER([ProductName]+[ProductName])),'chaichai','chai'))"

#find the number of equations in the string. Count of '(' will give you the number
n = expression.count('(')

#split the string by left parenthesis. You get all the functions + middle part + right hand side 
exp_left = expression.split('(')
#middle + right hand part is at position index -1. Use pop to remove the last value
#Use the popped string to split by right parenthesis
#result will be middle part + all right hand side parts.
#empty string if there was no text between two right parenthesis
exp_right = exp_left.pop().split(')')

#define a list to store all the expressions
exp_list = []

#Now put it all together looping thru n times
#store the expression in a string so you can concat left and right to it each time
exp_string = ''

for i in range(n):
    #for each iteration, concat left side + ( + middle string + right side + )
    #left hand side: concat from right to left (-1 to 0)
    #right hand side: concat from left to right (0 to n-1)
    exp_string = exp_left[-i-1] + '(' + exp_string + exp_right[i] + ')'
    #append the expression to the expression list
    exp_list.append(exp_string)

#print each string separately
for exp in exp_list: print (exp)

使用While语句的方法

下面是如何进行搜索和提取版本

e = "LEN(Replace(Lower(UPPER([ProductName]+[ProductName])),'chaichai','chai'))"

x = e.count('(')

for i in range(x-1): e = e[e.find('(')+1:]
expression = e[:e.find(')')+1]

print (expression)

其结果将是:

UPPER([ProductName]+[ProductName])

如果你想要所有这些,那么你可以这样做,直到你到达最里面的括号

e = "LEN(Replace(Lower(UPPER([ProductName]+[ProductName])),'chaichai','chai'))"

#x = e.count('(')
#for i in range(x-1): e = e[e.find('(')+1:]
#expression = e[:e.find(')')+1]


exp_list = [e]
while e.count('(') > 1:
    e = e[e.find('(')+1:e.rfind(')')]
    while e[-1] != ')': e = e[:e.rfind(')')+1]

    exp_list.append(e)

for exp in exp_list:
    print (exp)

其输出将为:

LEN(Replace(Lower(UPPER([ProductName]+[ProductName])),'chaichai','chai'))
Replace(Lower(UPPER([ProductName]+[ProductName])),'chaichai','chai')
Lower(UPPER([ProductName]+[ProductName]))
UPPER([ProductName]+[ProductName])

相关问题 更多 >