<p>好吧,我建议你做一个关系文本文件,你可以解析它,以防你认为关系以后会改变,或者只是为了让你的代码更容易阅读和修改。然后可以对其进行解析,以找到原料和配合物之间所需的关系。顺其自然吧”关系.txt,类型为:</p>
<pre><code>omelette: 5 x eggs + 1 x onions
pileofomelettes: 6 x omelette
</code></pre>
<p>在这里,您可以放置任意数量的成分类型:</p>
<blockquote>
<p>complex: number1 x ingredient1 + number2 x ingredient2 + ...</p>
</blockquote>
<p>等等。
还有你的食品.txt包含所有成分和复合物的价格:</p>
<pre><code>eggs: 2
onions: 1
omelette: 11.0
pileofomelettes: 60
</code></pre>
<p>现在我们可以看到pileofomlettes的值故意没有正确映射到这里。因此,我们将运行下面的代码,您也可以更改数字并查看结果。你知道吗</p>
<pre><code>#!/usr/bin/python
''' This program takes in a relations file and a food text files as inputs
and can be used to update the food text file based on changes in either of these'''
relations = {}
foodDict = {}
# Mapping ingredients to each other in the relations dictionary
with open("relations.txt") as r:
relationlist=r.read().splitlines()
for relation in relationlist:
item, equatedTo = relation.split(': ')
ingredientsAndCoefficients = equatedTo.split(' + ')
listIngredients = []
for ingredient in ingredientsAndCoefficients:
coefficient, item2 = ingredient.split(' x ')
# A list of sets of amount and type of ingredient
listIngredients.append((float(coefficient),item2))
relations.update({item:listIngredients})
# Creating a food dictionary with values from food.txt and mapping to the relations dictionary
with open("food.txt") as g:
foodlist=g.read().splitlines()
for item in foodlist:
food,value = item.split(': ')
foodDict.update({food:value})
for food in relations.keys():
# (Raw) Ingredients with no left hand side value in relations.txt will not change here.
value = 0.
for item2 in range(len(relations[food])):
# Calculating new value for complex here.
value += relations[food][item2][0]* float(foodDict[relations[food][item2][1]])
foodDict.update({food: value })
# Altering the food.txt with the new dictionary values
with open("food.txt",'w') as g:
for key in sorted(foodDict.keys()):
g.write(key + ': ' + str (foodDict[key])+ '\n')
print key + ': ' + str(foodDict[key])
</code></pre>
<p>结果是:</p>
<pre><code>eggs: 2
onions: 1
omelette: 11.0
pileofomelettes: 66.0
</code></pre>
<p>你可以把鸡蛋的价格改为5英镑食品.txt文件,以及</p>
<pre><code>eggs: 5
onions: 1
omelette: 26.0
pileofomelettes: 156.0
</code></pre>