这是我正在尝试创建的解析器,并且运行良好,但是以某种方式,我不能用一个以上的位数进行算术表达式。它适用于最多9个组件,但不支持10或21。第二个功能仅用于集成访问文本文件。
例如,我可以做9 * 9
,但是我不能做12 * 8
。
# AditPradipta_Equation_Solving
def only_parsing(equation):
operators = {0: lambda x, y : int(x) + int(y),
1: lambda x, y : int(x) - int(y),
2: lambda x, y : int(x) * int(y),
3: lambda x, y : int(x) / int(y)}
operators_list = ["+", "-", "*", "/"]
equation = equation.strip()
equation = equation.strip("=")
print(equation)
operator_num = 0
for operator in operators_list:
if operator_num == 3:
zero_division_check = equation.find("0")
if not zero_division_check != True:
continue
elif not zero_division_check != False:
return "You cannot divide by 0."
operator_find = equation.find(operators_list[operator_num])
if not operator_find != True:
first_num = equation[0]
second_num = equation[-1]
return operators[operator_num](int(first_num), int(second_num))
else:
operator_num = operator_num + 1
def multi_line_parsing(filename, new_file_name):
file = open(filename, 'r')
file_lines = file.readlines()
print(file_lines)
new_file = []
for line in file_lines:
print(line)
new_file.append(str(only_parsing(line)) + str("\n"))
print(new_file)
new_file_string_data = ''.join(new_file)
print(new_file_string_data)
file.close()
write_file = open(new_file_name, 'w+')
write_file.write(new_file_string_data)
write_file.close()
return
file_name = input("Please enter a filename: ")
new_file = input("Please enter another new file name: ")
multi_line_parsing(file_name, new_file)
期望输入和输出以及实际输入和输出的示例是
#Expected input
12 * 8
100 * 10
#Expected Output
96
1000
#Actual Output
None
None
任何帮助将不胜感激。
答案 0 :(得分:0)
评论:
str.split()
...仅好...用定界空格格式化。
它无法正确标记“ 12 * 8”
要同时处理其他格式和其他格式,请用re.split(...)
代替,例如:
import re
# Split by blank, require ALWAYS three parts delimited with blank
v1, v2 = re.split('[\+\-\*\/]', equation)
op = equation[len(v1)]
输出:
12*8 = 96 12* 8 = 96 100 *10 = 1000 division by zero: You cannot divide by 0 12 / 0 = None
问题:算术表达式...不适用于多个地方值
使用str.split()
可以处理任何长度的值。
简化您的方法,例如:
def only_parsing(equation):
# Use the operators as dict key
operators = {'+': lambda x, y: int(x) + int(y),
'-': lambda x, y: int(x) - int(y),
'*': lambda x, y: int(x) * int(y),
'/': lambda x, y: int(x) / int(y)}
# Split by blank, require ALWAYS three parts delimited with blank
v1, op, v2 = equation.split()
#print("{}".format((v1, op, v2)))
# Use try:...except to catch ZeroDivisionError
try:
# Call the lambda given by dict key
return operators[op](v1, v2)
except ZeroDivisionError as e:
print("{}: You cannot divide by 0".format(e,))
for exp in ['12 * 8', '100 * 10', '12 / 0']:
print("{} = {}".format(exp, only_parsing(exp)))
数量:
12 * 8 = 96 100 * 10 = 1000 division by zero: You cannot divide by 0 12 / 0 = None
使用Python:3.4.2测试