0

我有一些这样的字符串,在 之前或之后会有 0 个或多个空格,并且在字符串的末尾=会有 0 或 1 。### comment

log_File = a.log   ### the path for log
log_level = 10 

现在我想替换右边的字符串=。例如,将它们设置为如下:

log_File = b.log   ### the path for log
log_level = 40 

import re
s="log_File = a.log   ### the path for log"
re.sub("(?<=\s)\w+\S+",'Hello",s)

上面的代码把=后面的所有字符串都替换成Hello,我不想替换后面的字符串###,怎么实现呢。

4

2 回答 2

-1

试试下面的代码:

>>> re.sub(r'(?<!#)=(.*?)(?=\s*#|$)', r'= Hello', s, 1)
'log_File = Hello   ### the path for log'

不使用正则表达式(Inbar Rose 的版本已修改)

def replace_value(s, new):
    content, sep1, comment = s.partition('#')
    key, sep2, value = content.partition('=')
    if sep2: content = key + sep2 + new
    return content + sep1 + comment

assert replace_value('log_File = b', ' Hello') == 'log_File = Hello'
assert replace_value('#log_File = b', ' Hello') == '#log_File = b'
assert replace_value('#This is comment', ' Hello') == '#This is comment'
assert replace_value('log_File = b # hello', ' Hello') == 'log_File = Hello# hello'
于 2013-07-08T07:26:01.577 回答
-2

我看不出问题出在哪里。

下面的代码呢?

import re

pat = '(=\s*).+?(?=\s*(#|$))'
rgx = re.compile(pat,re.MULTILINE)

su = '''log_File = a.log   ### the path for log   
log_File = a.log   
log_File = a.log'''

print su
print
print rgx.sub('\\1Hello',su)

.

编辑

.

我已经看到问题出在哪里了!

正如我写的那样,我认为这个问题不能只通过正则表达式或相对简单的函数来简单地解决,因为在不触及赋值的情况下更改赋值的右侧部分(赋值的 AST 节点中称为的属性)可能的注释需要句法分析来确定分配的左侧部分(在分配的 AST 节点中称为目标的属性)、右侧部分是什么以及一行中可能的注释是什么。即使一行不是赋值指令,也需要进行句法分析来确定它。

对于这样的任务,我认为只有帮助 Python 应用程序处理 Python 抽象语法语法树ast的模块,它可以提供实现目标的工具。

这是我成功编写的关于这个想法的代码:

import re,ast       
from sys import exit

su = '''# it's nothing
import re
def funcg(a,b):\r
    print a*b + 900
x = "abc#ghi"\t\t# comment
k = 103
dico["abc#12"] = [(x,x//3==0) for x in xrange(25) if x !=12]
dico["ABC#12"] = 45   # comment
a = 'lulu#88'
dico["mu=$*"] = 'mouth#30'  #ohoh
log_File = a.log
y = b.log ### x = a.log  
'''

print su

def subst_assign_val_in_line(line,b0,repl):
    assert(isinstance(b0,ast.AST))
    coloffset = b0.value.col_offset
    VA = line[coloffset:]
    try:
        yy = compile(VA+'\n',"-expr-",'eval')
    except: # because of a bug of ast in computing VA
        coloffset = coloffset - 1
        VA = line[coloffset:]
        yy = compile(VA+'\n',"-expr-",'eval')

    gen = ((i,c) for i,c in enumerate(VA) if c=='#')
    for i,c in gen:
        VAshort = VA[0:i] # <== cuts in front of a # character
        try:
            yyi = compile(VAshort+'\n',"-exprshort-",'eval')
        except:
            pass
        else:
            if yy==yyi:
                return (line[0:coloffset] + repl + ' ' +
                        line[coloffset+i:])
                break
            else:
                print 'VA = line[%d:]' % coloffset
                print 'VA :  %r' % VA
                print '  yy != yyi  on:'
                print 'VAshort : %r' % VAshort
                raw_input('  **** UNIMAGINABLE CASE ***')

    else:
        return line[0:coloffset] + repl
            


def subst_assigns_vals_in_text(text,repl,
                               rgx = re.compile('\A([ \t]*)(.*)')):

    def yi(text):
        for line in text.splitlines():
            head,line = rgx.search(line).groups()
            try:
                body = ast.parse(line,'line','exec').body
            except:
                yield head + line
            else:   
                if isinstance(body,list):
                    if len(body)==0:
                        yield head + line
                    elif len(body)==1:
                        if type(body[0])==ast.Assign:
                            yield head + subst_assign_val_in_line(line,
                                                                  body[0],
                                                                  repl)
                        else:
                            yield head + line
                    else:
                        print "list ast.parse(line,'line','exec').body has more than 1 element"
                        print body
                        exit()
                else:
                    print "ast.parse(line,'line','exec').body is not a list"
                    print body
                    exit()

    return '\n'.join(yi(text))

print subst_assigns_vals_in_text(su,repl='Hello')

事实上,我在编写它时附有说明print和个人程序的帮助,以便以可读的方式(对我而言)显示 AST 树。
以下是仅包含说明的代码print,以遵循该过程:

import re,ast       
from sys import exit

su = '''# it's nothing
import re
def funcg(a,b):\r
    print a*b + 900
x = "abc#ghi"\t\t# comment
k = 103
dico["abc#12"] = [(x,x//3==0) for x in xrange(25) if x !=12]
dico["ABC#12"] = 45   # comment
a = 'lulu#88'
dico["mu=$*"] = 'mouth#30'  #ohoh
log_File = a.log
y = b.log ### x = a.log  
'''

print su
print '#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-'

def subst_assign_val_in_line(line,b0,repl):
    assert(isinstance(b0,ast.AST))
    print '\n%%%%%%%%%%%%%%%%\nline :  %r' % line
    print '\nb0 == body[0]: ',b0
    print '\nb0.value: ',b0.value
    print '\nb0.value.col_offset==',b0.value.col_offset
    coloffset = b0.value.col_offset
    VA = line[coloffset:]
    try:
        yy = compile(VA+'\n',"-expr-",'eval')
    except: # because of a bug of ast in computing VA
        coloffset = coloffset - 1
        VA = line[coloffset:]
        yy = compile(VA+'\n',"-expr-",'eval')
    print 'VA = line[%d:]' % coloffset
    print 'VA :  %r' % VA
    print ("yy = compile(VA+'\\n',\"-expr-\",'eval')\n"
           'yy =='),yy
    gen = ((i,c) for i,c in enumerate(VA) if c=='#')
    deb = ("mwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmw\n"
           "    mwmwmwm '#' in VA  mwmwmwm\n")
    for i,c in gen:
        print '%si == %d   VA[%d] == %r' % (deb,i,i,c)
        deb = ''
        VAshort = VA[0:i] # <== cuts in front of a # character
        print '  VAshort = VA[0:%d] == %r' % (i,VAshort)
        try:
            yyi = compile(VAshort+'\n',"-exprshort-",'eval')
        except:
            print "  compile(%r+'\\n',\"-exprshort-\",'eval') gives error" % VAshort
        else:
            print ("  yyi = compile(VAshort+'\\n',\"-exprshort-\",'eval')\n"
                   '  yyi =='),yy
            if yy==yyi:
                print '  yy==yyi   Real value of assignement found'
                print "mwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmw"
                return (line[0:coloffset] + repl + ' ' +
                        line[coloffset+i:])
                break
            else:
                print 'VA = line[%d:]' % coloffset
                print 'VA :  %r' % VA
                print '  yy != yyi  on:'
                print 'VAshort : %r' % VAshort
                raw_input('  **** UNIMAGINABLE CASE ***')
    else:
        return line[0:coloffset] + repl
            

def subst_assigns_vals_in_text(text,repl,
                               rgx = re.compile('\A([ \t]*)(.*)')):

    def yi(text):
        for line in text.splitlines():
            raw_input('\n\npause')
            origline = line
            head,line = rgx.search(line).groups()
            print ('#########################################\n'
                   '#########################################\n'
                   'line     : %r\n'
                   'cut line : %r' % (origline,line))
            try:
                body = ast.parse(line,'line','exec').body
            except:
                yield head + line
            else:
                if isinstance(body,list):
                    if len(body)==0:
                        yield head + line
                    elif len(body)==1:
                        if type(body[0])==ast.Assign:
                            yield head + subst_assign_val_in_line(line,
                                                                  body[0],
                                                                  repl)
                        else:
                            yield head + line
                    else:
                        print "list ast.parse(line,'line','exec').body has more than 1 element"
                        print body
                        exit()
                else:
                    print "ast.parse(line,'line','exec').body is not a list"
                    print body
                    exit()

    #in place of return '\n'.join(yi(text)) , to print the output
    def returning(text):
        for output in yi(text):
            print 'output   : %r' % output
            yield output

    return '\n'.join(returning(text))
                        

print '\n\n\n%s' % subst_assigns_vals_in_text(su,repl='Hello')

我不做解释,因为解释由ast.parse(). 如果被问到,我会在我的代码上给出一些提示

注意当它给出开始某些节点的行和列时,存在一个错误ast.parse(),所以我不得不通过额外的指令行来纠正这个错误。
例如,它在列表理解上给出错误的结果。

于 2013-07-08T08:18:50.993 回答