我有一些像这样的字符串,=
之前或之后会有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,我不想在###
之后替换字符串,我该如何实现呢。
答案 0 :(得分:-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'
答案 1 :(得分:-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)
我已经看到了问题所在!
在我写这篇文章的时候,我不认为问题只能通过正则表达式或相对简单的函数来解决,因为改变了一个分配的右边部分(属性叫做 value )在没有触及可能的注释的情况下,一个分配的AST节点需要一个句法分析来确定一个分配的左边部分(在一个分配的AST节点中称为目标的属性),是什么右边部分,一行中可能的评论是什么。即使一条线不是一个分配指令,也需要一个句法分析来确定它。
对于这样的任务,只有模块ast
,其中帮助Python应用程序处理Python抽象语法语法的树,它可以提供实现目标的工具,在我的意见。
这是我成功写下这个想法的代码:
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树结构太长了。如果被问及
NB ast.parse()
的功能存在错误,当它给出了开始某些节点的行和列时,所以我不得不通过附加的指令行来纠正它。 />
例如,它给列表理解提供了错误的结果。