我们可以在python中将字符串转换为等价的数字和运算符,然后对该表达式求值以得到答案。例如,我们将“2+3”转换为“2+3”,然后使用
eval
words_to_symbols = {
'one': '1',
'two': '2',
'three': '3',
'four': '4',
'five': '5',
'six': '6',
'seven': '7',
'eight': '8',
'nine': '9',
'plus': '+',
'minus': '-',
'times': '*',
'divide': '/'
}
def parse_and_eval(string):
# Turn words into the equivalent formula
operation = ''.join(words_to_symbols[word] for word in string.split())
return eval(operation)
parse_and_eval('two plus three') # returns 5