Python 3的配方修改程序解决方案

1 投票
1 回答
893 浏览
提问于 2025-04-17 23:48

我想知道有没有人能解决这个问题。
我在做OCR GCSE计算机课程的食谱任务时,总是遇到错误,程序运行不正常。我已经成功地把添加食谱的功能做到了外部文本文件里,也能搜索到已有的食谱。

我现在遇到的问题是,如何根据不同的人数重新计算食谱中的新数量(所有的数据都是数字)。我使用的是Python 3版本。

我修改程序的部分如下。(我把所有食谱默认设置为1人份)这样更容易重新计算新的数量。

我的代码如下。**

非常感谢你的帮助。

import os

def modify():
    #create a boolean variable to use as a flag
    found = False

    #Get the search value and the new recipe information.
    search = input ("Enter a recipe name to search for: ")
    new_number_of_people =input("Enter the new number of people to serve (default is 1):")


    #open the original recipeList.txt file.
    recipeList_file=open("recipeList.txt", "r")

    #open the temporary file.
    temp_file = open("temp.txt", "w")

    #Read the first record's recipe name field
    recipe = recipeList_file.readline()


    #Read the rest of the file.
    while recipe != "":
         #Read the recipe item,quantity, units and number of people.
        ingredient1 = str(recipeList_file.readline())
        quantity1 =float(recipeList_file.readline())
        units1 = str (recipeList_file.readline())
        ingredient2 = str(recipeList_file.readline())
        quantity2 =float(recipeList_file.readline())
        units2 = str (recipeList_file.readline())        
        ingredient3 = str(recipeList_file.readline())
        quantity3 =float(recipeList_file.readline())
        units3 = str (recipeList_file.readline())        
        number_of_people = float(recipeList_file.readline())

        recipe = recipe.rstrip("\n")


         #write a new record with the temp file
        if recipe == search:
             #write the modified record to the temp file.
             temp_file.write(recipe + "\n")
             temp_file.write(ingredient1+ "\n")
             temp_file.write((quantity1*input(new_number_of_people)) + "\n")
             temp_file.write(units1 + "\n")
             temp_file.write(ingredient2+ "\n")
             temp_file.write((quantity2*input(new_number_of_people)) + "\n")
             temp_file.write(units2 + "\n")
             temp_file.write(ingredient3+ "\n")
             temp_file.write((quantity3*input(new_number_of_people)) + "\n")
             temp_file.write(units3 + "\n")
             temp_file.write((new_number_of_people) + "\n")

             #Set the found flag to True.
             found = True
        else:
                 #write the original record to the temp file.
                 #write the modified record to the temp file.
             temp_file.write(recipe + "\n")
             temp_file.write(ingredient1+ "\n")
             temp_file.write((quantity1*input(new_number_of_people)) + "\n")
             temp_file.write(units1 + "\n")
             temp_file.write(ingredient2+ "\n")
             temp_file.write((quantity2*input(new_number_of_people)) + "\n")
             temp_file.write(units2 + "\n")
             temp_file.write(ingredient3+ "\n")
             temp_file.write((quantity3*input(new_number_of_people)) + "\n")
             temp_file.write(units3 + "\n")
             temp_file.write((new_number_of_people) + "\n")


         #Read the next recipe
        ingredient1 = str(recipeList_file.readline())
        quantity1 = float(recipeList_file.readline())
        units1 = str (recipeList_file.readline())
        ingredient2 = str(recipeList_file.readline())
        quantity2 = float(recipeList_file.readline())
        units2 = str (recipeList_file.readline())
        ingredient3 = str(recipeList_file.readline())
        quantity3 = float(recipeList_file.readline())
        units3 = str (recipeList_file.readline())
        number_of_people = float(recipeList_file.readline())

        #Close the Recipe file and the temporary file.
    recipeList_file.close()
    temp_file.close()

        #Delete the original recipeList.txt file.
    os.remove ("recipeList.txt")

        #Rename the temporary file.
    os.rename("temp.txt", "recipeList.txt")

        #if the search was not found in the file display message
    if found:
        print ("The file has been updated.")

    else:
        print ("That recipe was not found in the file")
        #call the main function.
modify()

recipeList.txt的格式:

Cake 
Flour 
20 
grams 
Eggs 
2 
Number 
Butter 
2 
spoons 
1

1 个回答

0

输入文件的格式不是很好。我想把每个食谱放在一行里,每个数据之间用逗号分隔,这样就变成了csv格式。

不过既然输入就是这个格式……

首先,给每个任务写一个函数是个好习惯。所以我想到了三个任务:

  1. 从用户那里获取输入:question()
  2. 读取数据并处理:modify()
  3. 把处理后的数据保存到文件里:save()

question() 函数。解释:

这个函数会询问用户输入的数据,然后把结果以元组的形式返回。

modify() 函数。解释:

打开输入文件后,我会读取整个文件,并用'\n'这个符号把每一行分开。这样就得到了一个包含每行内容的列表。

因为文件中每个食谱的名字都是唯一的,我想在调用函数时能准确找到某个食谱,所以我觉得用字典更好。字典的键是食谱的名字,而其他数据(我把它放在一个列表里)就是值。没错,字典的值可以是Python中的任何对象,所以我用一个列表。我先定义一个空字典,以便添加食谱。

每个食谱有12个数据(包括最后的空行),所以我用 zip(*[iter(recipeList)]*12) 创建了一个包含12个元素的元组,这样我就可以用 for 循环来遍历它。

元组的第0个索引是食谱的名字,我用它作为键。元组的其余部分(用切片 [1:] 从第二个元素到最后一个元素)转换成列表后就是字典的值。为什么用列表?因为在Python中,元组是不可变的。

然后我遍历这个列表(从第二个元素开始,每次跳过3个元素;这些是数量),用每个数量乘以吃饭的人数来更新值。最后,我把列表的第十个项目更新为人数。

这个函数返回更新后的字典。

save() 函数。 试着自己写这个函数。你只需要遍历字典(用嵌套列表),然后把每个数据写到新的食谱文件中,每行一个数据。(别忘了写出每个字典对的键,也就是食谱的名字)。

import os

def modify(recipe_name, number):
    recipeList_file = open('recipeList.txt', 'r', newline= None)
    recipeList = recipeList_file.read().split('\n')
    recipeDict = {}
    for i in zip(*[iter(recipeList)]*12):
        print(i)    # For debugging purpose
        recipeDict[i[0]] = list(i[1:])
        print(recipeDict.items())    # For debugging purpose
    for j in range(1, 10, 3):
        recipeDict[recipe_name][j] = str(int(recipeDict[recipe_name][j]) * number)
    recipeDict[recipe_name][9] = str(number)
    print(recipeDict.items())    # For debugging purpose
    recipeList_file.close()
    return recipeDict

def question():
    search = input("Enter a recipe name to search for: ")
    new_number_of_people = int(input("Enter the new number of people to serve (default is 1):"))
    return search, new_number_of_people


def save(dictionarySave):
    pass
    # Think yourself.

recipe_to_modify, number_to_modify = question()
new_recipe_dictionary = modify(recipe_to_modify, number_to_modify)
save(new_recipe_dictionary)

撰写回答