请大神指导下:
python代码如下:
import fileinput,re
# Matches fields enclosed in square brackets:
field_pat = re.compile(r'\[(.+?)\]')
# We'll collect variables in this:
scope = {}
# This is used in re.sub:
def replacement(match):
code = match.group(1)
try:
# If the field can be evaluated, return it:
return str(eval(code, scope))
except SyntaxError:
# Otherwise, execute the assignment in the same scope ... exec code in scope
# ... and return an empty string:
return ''
# Get all the text as a single string:
# (There are other ways of doing this; see Chapter 11)
lines = []
for line in fileinput.input():
lines.append(line)
text = ''.join(lines)
# Substitute all the occurrences of the field pattern:
x=[]
print(field_pat.sub(replacement, text))
然后报错信息:
c:\python>python hello.py text1.txt
Traceback (most recent call last):
File "hello.py", line 28, in <module>
print(field_pat.sub(replacement, text))
File "hello.py", line 15, in replacement
return str(eval(code, scope))
File "<string>", line 1, in <module>
NameError: name 'x' is not defined
其中text1.txt中的内容:
[x=2]
[y=3]
The sum of [x] and [y] is [x + y].