Py学习  »  Python

如何在python中使用单词代替数值和运算符进行加法

smugthug • 4 年前 • 911 次点击  

这里是python新手。 我正在研究一个问题来编写一个脚本,该脚本以单词问题的形式获取用户输入,例如2+3和7+5,但返回一个数值作为输出。例如,如果用户输入“2+3”,则输出应为5(假设用户只输入数字0-9和操作加、减、次和除以)。

我想我需要把字符串分解成数字和操作。我应该用。分开吗?如何将拼写出来的数字作为数值进行处理?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/51029
 
911 次点击  
文章 [ 1 ]  |  最新文章 4 年前
Iain Shelvington
Reply   •   1 楼
Iain Shelvington    4 年前

我们可以在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