Я делаю проект программы рецептов для GCSE Computing. Он хранит рецепты в TXT-документах, а затем по запросу открывает и представляет информацию для чтения.Python: Recipe Program
В данный момент времени он хранит рецепт в верхней части .txt-файла и ингредиентов внизу. Он запускает thorugh heading1 для рецепта и разбивает его на презентацию. Затем он должен пройти через рубрику2 и просмотреть каждую колонку, ингредиенты, вес и измерение. Затем, используя цикл for, будет проходить через списки и представлять ингредиенты вместе с их соответствующим весом и измерением.
код, как показано ниже:
#-------------------------------------------------------------------------------
# Name: Recipe Holder
# Purpose: Hold recipes
#
# Author: Ashley Collinge
#
# Created: 25/02/2013
# Copyright: (c) Ashley Collinge 2013
#-------------------------------------------------------------------------------
def menu():
print "Recipe Holder"
print "Use the numbers to navigate the menu."
print ""
print ""
print "1) View Recipes"
print "2) Add Recipes"
print "3) Delete Recipe"
print ""
choice_completed = False
while choice_completed == False:
choice = raw_input("")
if choice == "1":
choice_completed = True
view_recipe()
elif choice == "2":
choice_completed = True
add_recipe()
elif choice == "3":
choice_completed = True
delete_recipe()
else:
choice_completed = False
def view_recipe():
print ""
print ""
mypath = "/recipe"
from os import listdir
from os.path import isfile, join
onlyfiles = [ f for f in listdir("H:/Recipes/recipes") if isfile(join("H:/Recipes/recipes",f)) ]
a = -1
for i in onlyfiles:
a = a +1
print a, i
print ""
print "Type in the number of the recipe you would like to view, below and press enter."
print ""
choice = input("")
import os, sys
print onlyfiles[choice]
something = str(onlyfiles[choice])
directory = "recipes" + "\\" + something
from itertools import takewhile, imap
with open(directory) as f:
items = list(takewhile("heading1".__ne__, imap(str.rstrip, f)))
print "Recipe for " + directory
for h in range(len(items)): #following three lines to take the list of recipe and split it by line in to instructions then display
print str(h)+". "+str(items[h])
def getColumn(title,file):
result = []
global result
with open(file) as f:
headers = f.readline().split(',')
index = headers.index(title)
for l in f.readlines():
result.append(l.rstrip().split(',')[index])
return result
ingredients = (getColumn("ingredients",directory))
weight = (getColumn("weight",directory))
measurement = (getColumn("measurement",directory))
print directory
print "Ingredients"
for i in range(len(ingredients)):
print ingredients[i]+" "+weight[i]+" "+measurement[i]
input("")
def delete_recipe():
print "Delete Recipe"
print "Type in the number of the recipe you would like to delete, below and press enter."
mypath = "/recipe"
from os import listdir
from os.path import isfile, join
onlyfiles = [ f for f in listdir("H:/Recipes/recipes") if isfile(join("H:/Recipes/recipes",f)) ]
a = -1
for i in onlyfiles:
a = a +1
print a, i
choice = input("")
import os, sys
print onlyfiles[choice]
something = str(onlyfiles[choice])
directory = "recipes" + "\\" + something
os.remove(directory)
menu()
Текстовый файл, как показано ниже:
Recipe As now
Put sugar in bowl
heading1
ingredients,weight,measurement,
Sugar,100,grams
heading2
Я получаю следующее как ошибка:
raspberry_pie - Copy (8).txt
Recipe for recipes\raspberry_pie - Copy (8).txt
0. Recipe As now
1. fhgje
2. fe
Traceback (most recent call last):
File "H:\Recipes\Recipe Program.py", line 96, in <module>
menu()
File "H:\Recipes\Recipe Program.py", line 24, in menu
view_recipe()
File "H:\Recipes\Recipe Program.py", line 69, in view_recipe
ingredients = (getColumn("ingredients",directory))
File "H:\Recipes\Recipe Program.py", line 65, in getColumn
index = headers.index(title)
ValueError: 'ingredients' is not in list
Просто скажите, престиж для того, чтобы сначала изучить надлежащие навыки в вычислениях GCSE, а во-вторых, чтобы прийти в прекрасное место, чтобы изучить его! –
Есть ли ошибка форматирования в вашем коде? 'getColumn', кажется, никогда не вызывается извне (что кажется странным само по себе). –
Не могли бы вы объяснить семантику за «Рецептом как» и «headingX». Мое понимание заключается в том, что курс будет шагом, а затем ингредиенты и их пропорции перечислены под водой. I.e Heading = Whip eggs | ингредиенты, вес, измерение | 2 яйца, 100 г, 1 стакан – HennyH