适用于python版本3的ammend配方程序解决方案

时间:2014-03-25 10:27:27

标签: python

我想知道是否有人有解决方案。 我不断收到错误,我的程序因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 :(得分:0)

输入文件的格式不是最好的。我会更好地连续每个食谱,每个数据都有一个分隔符(逗号),一个csv格式。

但是输入是以那种格式给出的......

首先,为每项任务制定一项功能是一个好习惯。因此,我认为有3个任务:

  1. 来自用户的输入:question()
  2. 读取数据并进行处理:modify()
  3. 将处理后的数据保存到文件中:save()
  4. question()功能。说明:

    向用户询问输入数据,然后返回元组。

    modify()功能。说明:

    打开文件输入后,我读取()所有文件,并使用' \ n'分割每一行。分隔器。这会生成一个列表,其中包含文件每行的内容。

    由于配方名称在文件中是唯一的,我想在调用函数时访问确定的配方,我认为最好使用字典名称 配方是关键,其他数据(我把它放在一个列表中)是值。是, dict的值可以是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)