我看不出问题出在哪里。
下面的代码呢?
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()
,所以我不得不通过额外的指令行来纠正这个错误。
例如,它在列表理解上给出错误的结果。