全部版块 我的主页
论坛 数据科学与人工智能 数据分析与数据科学 python论坛
1114 7
2018-10-04
请大神指导下:

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].


二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

全部回复
2018-10-5 16:02:43
你这个就是说X没有定义,
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2018-10-5 17:23:38
齐物论pi 发表于 2018-10-5 16:02
你这个就是说X没有定义,
怎么改?
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2018-10-5 17:28:59
你把代码发给我,或者加我的机器学习群:347947372
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2018-10-5 17:54:49
是要执行text1.txt中的[x=2][y=3]并替换The sum of [x] and [y] is [x + y].吗

复制代码


你试试。
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2018-10-5 17:56:23
longgb246 发表于 2018-10-5 17:54
是要执行text1.txt中的[x=2][y=3]并替换The sum of [x] and [y] is [x + y].吗
其他地方没有改过,不用复制过去,就只是# Otherwise下面加了2句代码
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

点击查看更多内容…
相关推荐
栏目导航
热门文章
推荐文章

说点什么

分享

扫码加好友,拉您进群
各岗位、行业、专业交流群