我需要在python中创建一个计算器。一开始,我有一个带数字的字符串和一个像这样的单词:str = '5 plus 5'
我可以对两个数字执行此操作,但是当字符串看起来像:hard_str = '5 plus 10 divide 2'
时,我需要知道在这种情况下如何进行计算。基本上,当我说str = '2 minus 20 divide 4'
时,谷歌语音助手如何进行计算?
def math(text):
'''text是一个字符串,例如“ 22加5”'''
ADD = ['+', 'plus',]
SUBTRACT = ['-', 'minus',]
MULTIPLY = ['*', 'multiply', 'x']
DIVIDE = ['/', 'divide',]
expression = text
expression = expression.lower().split()
expression_left = expression[0]
expression_middle = expression[1]
expression_right = expression[2]
answer = None
if expression_middle in ADD:
answer = int(expression_left) + int(expression_right)
if expression_middle in SUBTRACT:
answer = int(expression_left) - int(expression_right)
if expression_middle in MULTIPLY:
answer = int(expression_left) * int(expression_right)
if expression_middle in DIVIDE:
answer = int(expression_left) / float(expression_right)
result = str(answer)
return f'Result of, {text} is {result}'
可处理2个数字,如果存在2 + 2 * 50 \ 8 * 3
怎么办答案 0 :(得分:0)
不幸的是,没有eval()我无法解决这个问题……暂时……这是我的方法:
divide = '/'
multiply = '*'
minus = '-'
plus = '+'
def hard_math(*text):
result = eval(text[0].replace('плюс', plus).replace('минус', minus).replace('x', multiply).replace('x', multiply).replace('/',divide))
return str(result)