python中如何用单词代替数值和运算符做加法
How to use words instead of numerical values and operators to do addition in python
这里是 python 的新手。
我正在研究一个问题来编写一个脚本,该脚本以单词问题的形式获取用户输入,例如“二加三”和“七减五”,但 returns 一个数值作为输出。例如,如果用户输入 "two plus three",则输出应为 5(假设用户仅输入数字 0-9 和运算加、减、乘以和除以)。
我想我需要将字符串分解为数字和操作。我应该使用 .split 吗?以及如何将拼写出来的数字作为数值进行处理?
我们可以将字符串转换为 python 中的等效数字和运算符,然后计算该表达式以获得答案。例如,我们将 "two plus three" 转换为“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
这里是 python 的新手。 我正在研究一个问题来编写一个脚本,该脚本以单词问题的形式获取用户输入,例如“二加三”和“七减五”,但 returns 一个数值作为输出。例如,如果用户输入 "two plus three",则输出应为 5(假设用户仅输入数字 0-9 和运算加、减、乘以和除以)。
我想我需要将字符串分解为数字和操作。我应该使用 .split 吗?以及如何将拼写出来的数字作为数值进行处理?
我们可以将字符串转换为 python 中的等效数字和运算符,然后计算该表达式以获得答案。例如,我们将 "two plus three" 转换为“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