我们有一些数学问题的文件,例如:46 + 19(只有 + 或 - 并且它是这样构建的:数字,空格,符号,空格,数字),我们需要将其转换为一个新文件并解决它们(46 + 19 = 65)。我们不知道会有多少练习或每个数字的位数。这是我的代码:enter code hereinput_file = open(r'C:\try\bla.txt', 'r')nums = input_file.read()y = 0dig1 = ''dig2 = ''sign = ''x1 = nums.find(' ')x2 = x1 + 1def one(dig1, dig2, y): for i in xrange(x1): dig1 += nums[y] y += 1 for m in xrange(abs(-x2)): dig2 += nums[y + 1] y += 1sign = nums[x2]if sign == '+': sum = int(dig1) + int(dig2)if sign == '-': sum = int(dig1) - int(dig2)print dig1, dig2, '=', sumfor a in xrange(0): one(dig1, dig2, y)one(dig1, dig2, y)print 'f', nums[21]#print dig1, dig2, '=', sum
1 回答
拉丁的传说
TA贡献1789条经验 获得超8个赞
也许你想得到这个(python3):
test.txt:
10 + 15
22 - 71
33 + 64
代码:
import operator
op = {'+': operator.add, '-': operator.sub}
with open('test.txt', 'r') as f:
lines = f.readlines()
for i in lines:
args = i.split()
val = op[args[1]](int(args[0]), int(args[-1]))
r = f'{i.strip()} = {val}'
print(r)
添加回答
举报
0/150
提交
取消