我想编写一个带字符串的函数,找到tsp或tbsp格式,然后将其转换为gram。
然后,我将此信息存储在c中,并且必须将其插入字符串中的tbsp / tsp单词后面。由于字符串是不可变的,我想首先将它转换为列表,但现在我有点卡住了。
任何人都有关于如何做到这一点的建议? :)
示例:
input output
" 2汤匙黄油" - > " 2汤匙(30克)黄油"
" 1/2汤匙牛至" - > " 1/2汤匙(8克)的牛至"
" 1/2茶匙盐" - > " 1/2汤匙(3克)盐"
def convert_recipe(recipe):
c = ''
for i in recipe: # save the digit
if i.isdigit():
c += i
if 'tsp' in recipe: # convert tsp to gram
c = int(c) * 5
elif 'tbsp' in recipe: # convert tbsp to gram
c = int(c) * 15
# now we have c. Insert (c) behind tsp / tbsp in string
recipe = recipe.split()
print(recipe)
convert_recipe("2 tbsp of butter")
答案 0 :(得分:1)
这是一个应该涵盖大多数情况的解决方案。
from fractions import Fraction
from math import ceil
def convert_recipe(recipe):
weight = {'tbsp': 15, 'tsp': 5} # store the weights for tsp and tbsp
ts = 'tbsp' if 'tbsp' in recipe else 'tsp'
temp = recipe.split() # convert string to list
quantity = float(Fraction(temp[temp.index(ts)-1]))
new_recipe = recipe.replace(ts, '{} ({}g)'.format(ts, ceil(quantity*weight[ts]))) # see (1)
return new_recipe
print(convert_recipe("2 tbsp of butter")) # -> 2 tbsp (30g) of butter
print(convert_recipe("1/2 tbsp of butter")) # -> 1/2 tbsp (8g) of butter
print(convert_recipe("1/2 tsp of salt")) # -> 1/2 tsp (3g) of salt
(1):这里实际上是以'tbsp'
替换句子的'tbsp (30g)'
部分。插入的字符串('tbsp (30g)'
)是字符串格式化的结果。
答案 1 :(得分:0)
if 'tsp' in recipe: (1)
c = int(c) * 5
recipe = recipe.split('tsp') (2)
recipe = recipe[0] + 'tsp (' + str(c) + 'g)' + recipe[1]
// tbsp
的类似代码我相信这对你有用吗?
编辑:
at(1),recipe =“1/2茶匙盐”
在(2),食谱变为[“1/2”,“盐”]
然后将所有关于将字符串重新组合在一起
split方法根据给定的参数拆分字符串并返回字符串数组