将字符串数学指令转换为其等效操作
converting string mathematical instruction into its equivalent operation
我想将字符串数学指令转换成它的等效整数运算;
例如:
1.'double three'= 33
- 'triple six'=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
等指令工作
您为乘数和数字制作了单独的字典。如果一个单词在 multipliers 词典中,请记住它的 multiplier 值是多少。如果它在digits字典中,则乘以当前乘数。
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
我想将字符串数学指令转换成它的等效整数运算;
例如: 1.'double three'= 33
- 'triple six'=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
等指令工作
您为乘数和数字制作了单独的字典。如果一个单词在 multipliers 词典中,请记住它的 multiplier 值是多少。如果它在digits字典中,则乘以当前乘数。
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