如何将除法运算符/分配给文本词“ divided”或“ divides”

时间:2019-09-30 15:21:10

标签: python-3.x

我有一个文本, “ 45乘以8时余数为5”

我只想通过编程将除法运算符 '/' 分配给文本“ divide”并求值45/8并得到结果(余数5)。因此,我验证了文本是否正确。

我这样尝试过...

word= "45 divided by 8"
rep=word.replace('divided by','/')
print(rep)

但是我得到45/8,剩下的不是5

1 个答案:

答案 0 :(得分:0)

由于是翻译,所以字典是个好主意:

translations = {
    'divided by': '//',
    'multiplied by' : '*',
    'times' : '*',
    'seven': '7',
}

def evaluate(sentence):
    for k, v in translations.items():
        sentence = sentence.replace(k, v)
    result = eval(sentence)
    return result

#examples
sentences = [
    "45 divided by 8",
    "45 multiplied by 8",
    "4 times 2 divided by seven",
    "4 times 2 times seven",
]

for s in sentences:
    print(s, 'evaluates to ', evaluate(s))

# displays:
# 45 divided by 8 evaluates to  5
# 45 multiplied by 8 evaluates to  360
# 4 times 2 divided by seven evaluates to  1
# 4 times 2 times seven evaluates to  56

请注意,人们通常会推荐ast.literal_eval而不是eval,例如Using python's eval() vs. ast.literal_eval()?