Python字符串语法校正器

Python字符串语法校正器,python,Python,我编写了一个脚本,在解析器读取命令之前捕获并更正命令。解析器要求equal、not equal、Morter等条目用逗号分隔,例如: “测试(a>=b)”是错误的 “测试(a,>=,b)”是正确的 我写的剧本很好,但我很想知道是否有更有效的方法来实现这一点 这是我的剧本: # Correction routine def corrector(exp): def rep(exp,a,b): foo = '' while(True):

我编写了一个脚本,在解析器读取命令之前捕获并更正命令。解析器要求equal、not equal、Morter等条目用逗号分隔,例如:

“测试(a>=b)”是错误的
“测试(a,>=,b)”是正确的

我写的剧本很好,但我很想知道是否有更有效的方法来实现这一点

这是我的剧本:

# Correction routine
def corrector(exp):
    def rep(exp,a,b):
        foo = ''
        while(True):
            foo = exp.replace(a,b)
            if foo == exp:
                return exp
            exp = foo

    # Replace all instances with a unique identifier. Do it in a specific order
    # so for example we catch an instance of '>=' before we get to '='
    items = ['>=','<=','!=','==','>','<','=']
    for i in range(len(items)):
        exp = rep(exp,items[i],'###%s###'%i)

    # Re-add items with commas
    for i in range(len(items)):
        exp = exp.replace('###%s###'%i,',%s,'%items[i])

    # Remove accidental double commas we may have added
    return exp.replace(',,',',')


print corrector('wrong_syntax(b>=c) correct_syntax(b,>=,c)')
// RESULT: wrong_syntax(b,>=,c) correct_syntax(b,>=,c)
校正程序 def校正器(exp): def代表(试验、a、b): foo='' 虽然(正确): foo=exp.replace(a,b) 如果foo==exp: 返回经验 exp=foo #用唯一标识符替换所有实例。按特定的顺序做 #例如,我们在到达“=”之前捕获“>=”的一个实例 items=['>=',''''=c)正确的语法(b,>=,c)] //结果:错误的语法(b,>=,c)正确的语法(b,>=,c)
谢谢!

如评论中所述,一种方法是使用正则表达式。以下正则表达式匹配没有逗号包围的任何运算符,并用插入逗号的相同字符串替换它们:

inputstring = 'wrong_syntax(b>=c) correct_syntax(b,>=,c)'
regex = r"([^,])(>=|<=|!=|==|>|<|=)([^,])"
replace = r"\1,\2,\3"

result = re.sub(regex, replace, inputstring)

print(result)
inputstring='错误的语法(b>=c)正确的语法(b,>=c)'

regex=r“([^,])(>=| |如注释中所述,一种方法是使用正则表达式。以下regex在没有逗号包围的情况下匹配任何运算符,并用插入的逗号替换为相同的字符串:

inputstring = 'wrong_syntax(b>=c) correct_syntax(b,>=,c)'
regex = r"([^,])(>=|<=|!=|==|>|<|=)([^,])"
replace = r"\1,\2,\3"

result = re.sub(regex, replace, inputstring)

print(result)
inputstring='错误的语法(b>=c)正确的语法(b,>=c)'

regex=r“([^,])(>=| |这里有一个正则表达式,它可以满足您的要求:

import re
regex = re.compile(r'''

    (?<!,)                  # Negative lookbehind
    (!=|[><=]=?)
    (?!,)                   # Negative lookahead

''', re.VERBOSE)
print regex.sub(r',\1,', 'wrong_expression(b>=c) or right_expression(b,>=,c)')

下面是一个正则表达式,它可以满足您的要求:

import re
regex = re.compile(r'''

    (?<!,)                  # Negative lookbehind
    (!=|[><=]=?)
    (?!,)                   # Negative lookahead

''', re.VERBOSE)
print regex.sub(r',\1,', 'wrong_expression(b>=c) or right_expression(b,>=,c)')

我想您可能需要使用正则表达式。我很确定这就是您要发布此内容的地方--特别是阅读.sub()method@IanAuld谢谢,以后会这样做。我想你可能想使用正则表达式。我很确定这就是你想发布的地方——尤其是.sub() method@IanAuld谢谢,以后会这样做。我将以此作为我的答案。我不知道为什么除了字符串匹配之外,我从来没有想到过正则表达式。现在我有很好的理由对它进行替换:)谢谢!我将以此作为我的答案。我不知道为什么除了字符串匹配之外,我从来没有想到过正则表达式。现在我有很好的理由对它进行替换:)谢谢!谢谢!我不需要在将来回避regex,并对它感到舒适。谢谢!我不需要在将来回避regex,并对它感到舒适。