将字符串数学指令转换为其等效运算

发布于 2025-01-20 23:28:42 字数 464 浏览 0 评论 0原文

我想将字符串数学指令转换为等效整数操作;

例如: 1.'double三'= 33

  1. '三重六'= 666

我的代码是:

hashmap={
'one': '1',
'two': '2',
'three': '3',
'four': '4',
'five': '5',
'six': '6',
'seven': '7',
'eight': '8',
'nine': '9',
'zero' : '0'}


str1="one five three"
st2int = ''.join(hashmap[ele] for ele in str1.split())
print(st2int)

我的程序仅适用于str数字。 我该如何使其用于指导,例如double,triple,Quadraple等,如我所述

i want to convert a string mathematical instruction into it's equivalent integer operation;

eg:
1.'double three'= 33

  1. 'triple six'=666

my code is:

hashmap={
'one': '1',
'two': '2',
'three': '3',
'four': '4',
'five': '5',
'six': '6',
'seven': '7',
'eight': '8',
'nine': '9',
'zero' : '0'}


str1="one five three"
st2int = ''.join(hashmap[ele] for ele in str1.split())
print(st2int)

my program is only for the str numbers to integer..
how can i make it to work for instruction like double,triple,quadrapleetc as i mentioned in the example

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

萧瑟寒风 2025-01-27 23:28:42

您为乘数和数字创建一个单独的字典。如果某个单词在乘数词典中,请记住它的乘数值是多少。如果它在数字字典中,则乘以当前的乘数。

multipliers = {
    'double': 2,
    'triple': 3,
    'quadruple': 4
}
digits = {
    'one': '1',
    'two': '2',
    'three': '3',
    'four': '4',
    'five': '5',
    'six': '6',
    'seven': '7',
    'eight': '8',
    'nine': '9',
    'zero' : '0'
}

inputs = [ "one five three", "triple six", "double two", "triple double nine" ]
for i in inputs:
    multiplier = 1
    numbers = []
    for word in i.split():
        if word in multipliers:
            multiplier = multiplier * multipliers[word]
        if word in digits:
            numbers.append(multiplier * digits[word])
            multiplier = 1
    print(''.join(numbers))

这打印:

153
666
22
999999

You make a separate dict for multipliers and for digits. If a word is in the multipliers dictionary, remember what its multiplier value is. If it's in the digits dictionary, multiply by the current multiplier.

multipliers = {
    'double': 2,
    'triple': 3,
    'quadruple': 4
}
digits = {
    'one': '1',
    'two': '2',
    'three': '3',
    'four': '4',
    'five': '5',
    'six': '6',
    'seven': '7',
    'eight': '8',
    'nine': '9',
    'zero' : '0'
}

inputs = [ "one five three", "triple six", "double two", "triple double nine" ]
for i in inputs:
    multiplier = 1
    numbers = []
    for word in i.split():
        if word in multipliers:
            multiplier = multiplier * multipliers[word]
        if word in digits:
            numbers.append(multiplier * digits[word])
            multiplier = 1
    print(''.join(numbers))

This prints:

153
666
22
999999
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文