Python: Recipe Program
up vote
1
down vote
favorite
I'm doing a Recipe program project for GCSE Computing. It stores recipes in .txt documents and then when requested it will open and present the information for those to read.
At this moment in time, it stores the recipe at the top of the .txt file and the ingredients at the bottom. It runs thorugh heading1 for the recipe and splits it up for presenting. Then it should go through heading2 and look through each column, ingredients, weight and measurement. Then using a for loop, will go through the lists and present the ingredients together with their respective weight and measurement.
Code is as below:
#-------------------------------------------------------------------------------
# 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()
Text file is as below:
Recipe As now
Put sugar in bowl
heading1
ingredients,weight,measurement,
Sugar,100,grams
heading2
I get the following as an error:
raspberry_pie - Copy (8).txt
Recipe for recipesraspberry_pie - Copy (8).txt
0. Recipe As now
1. fhgje
2. fe
Traceback (most recent call last):
File "H:RecipesRecipe Program.py", line 96, in <module>
menu()
File "H:RecipesRecipe Program.py", line 24, in menu
view_recipe()
File "H:RecipesRecipe Program.py", line 69, in view_recipe
ingredients = (getColumn("ingredients",directory))
File "H:RecipesRecipe Program.py", line 65, in getColumn
index = headers.index(title)
ValueError: 'ingredients' is not in list
python recipe
|
show 15 more comments
up vote
1
down vote
favorite
I'm doing a Recipe program project for GCSE Computing. It stores recipes in .txt documents and then when requested it will open and present the information for those to read.
At this moment in time, it stores the recipe at the top of the .txt file and the ingredients at the bottom. It runs thorugh heading1 for the recipe and splits it up for presenting. Then it should go through heading2 and look through each column, ingredients, weight and measurement. Then using a for loop, will go through the lists and present the ingredients together with their respective weight and measurement.
Code is as below:
#-------------------------------------------------------------------------------
# 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()
Text file is as below:
Recipe As now
Put sugar in bowl
heading1
ingredients,weight,measurement,
Sugar,100,grams
heading2
I get the following as an error:
raspberry_pie - Copy (8).txt
Recipe for recipesraspberry_pie - Copy (8).txt
0. Recipe As now
1. fhgje
2. fe
Traceback (most recent call last):
File "H:RecipesRecipe Program.py", line 96, in <module>
menu()
File "H:RecipesRecipe Program.py", line 24, in menu
view_recipe()
File "H:RecipesRecipe Program.py", line 69, in view_recipe
ingredients = (getColumn("ingredients",directory))
File "H:RecipesRecipe Program.py", line 65, in getColumn
index = headers.index(title)
ValueError: 'ingredients' is not in list
python recipe
Just to say, kudos for firstly learning proper skills in GCSE computing, and secondly for coming to a great place to learn it!
– Henry Gomersall
Apr 22 '13 at 11:32
1
Is there a formatting error in your code as presented?getColumn
doesn't appear to ever be called from outside of itself (which seems a strange thing in itself).
– Henry Gomersall
Apr 22 '13 at 11:48
Could you please explain the semantics behind "Recipe As" and the "headingX". My understanding is that heading would be the step and then the ingredients and their proportaions are listed underneat. I.e Heading = Whip the eggs | ingredients,weight,measurement | 2 eggs,100g,1 cup
– HennyH
Apr 22 '13 at 11:54
@HennyH looking at Ashley's previous questions, he hasn't engaged in the slightest after dumping a question on the community. Not the best way to learn methinks.
– Henry Gomersall
Apr 22 '13 at 12:00
Unfortunately, I have to resort to putting most errors or issues I have with programming, on to forum websites for extra support, as the teacher who is supervising the controlled assessment doesn't know Python very well, and I can't ask any other teachers as it is a controlled assessment.
– Ashley Collinge
Apr 22 '13 at 15:55
|
show 15 more comments
up vote
1
down vote
favorite
up vote
1
down vote
favorite
I'm doing a Recipe program project for GCSE Computing. It stores recipes in .txt documents and then when requested it will open and present the information for those to read.
At this moment in time, it stores the recipe at the top of the .txt file and the ingredients at the bottom. It runs thorugh heading1 for the recipe and splits it up for presenting. Then it should go through heading2 and look through each column, ingredients, weight and measurement. Then using a for loop, will go through the lists and present the ingredients together with their respective weight and measurement.
Code is as below:
#-------------------------------------------------------------------------------
# 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()
Text file is as below:
Recipe As now
Put sugar in bowl
heading1
ingredients,weight,measurement,
Sugar,100,grams
heading2
I get the following as an error:
raspberry_pie - Copy (8).txt
Recipe for recipesraspberry_pie - Copy (8).txt
0. Recipe As now
1. fhgje
2. fe
Traceback (most recent call last):
File "H:RecipesRecipe Program.py", line 96, in <module>
menu()
File "H:RecipesRecipe Program.py", line 24, in menu
view_recipe()
File "H:RecipesRecipe Program.py", line 69, in view_recipe
ingredients = (getColumn("ingredients",directory))
File "H:RecipesRecipe Program.py", line 65, in getColumn
index = headers.index(title)
ValueError: 'ingredients' is not in list
python recipe
I'm doing a Recipe program project for GCSE Computing. It stores recipes in .txt documents and then when requested it will open and present the information for those to read.
At this moment in time, it stores the recipe at the top of the .txt file and the ingredients at the bottom. It runs thorugh heading1 for the recipe and splits it up for presenting. Then it should go through heading2 and look through each column, ingredients, weight and measurement. Then using a for loop, will go through the lists and present the ingredients together with their respective weight and measurement.
Code is as below:
#-------------------------------------------------------------------------------
# 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()
Text file is as below:
Recipe As now
Put sugar in bowl
heading1
ingredients,weight,measurement,
Sugar,100,grams
heading2
I get the following as an error:
raspberry_pie - Copy (8).txt
Recipe for recipesraspberry_pie - Copy (8).txt
0. Recipe As now
1. fhgje
2. fe
Traceback (most recent call last):
File "H:RecipesRecipe Program.py", line 96, in <module>
menu()
File "H:RecipesRecipe Program.py", line 24, in menu
view_recipe()
File "H:RecipesRecipe Program.py", line 69, in view_recipe
ingredients = (getColumn("ingredients",directory))
File "H:RecipesRecipe Program.py", line 65, in getColumn
index = headers.index(title)
ValueError: 'ingredients' is not in list
python recipe
python recipe
edited Apr 22 '13 at 16:02
asked Apr 22 '13 at 11:28
Ashley Collinge
536
536
Just to say, kudos for firstly learning proper skills in GCSE computing, and secondly for coming to a great place to learn it!
– Henry Gomersall
Apr 22 '13 at 11:32
1
Is there a formatting error in your code as presented?getColumn
doesn't appear to ever be called from outside of itself (which seems a strange thing in itself).
– Henry Gomersall
Apr 22 '13 at 11:48
Could you please explain the semantics behind "Recipe As" and the "headingX". My understanding is that heading would be the step and then the ingredients and their proportaions are listed underneat. I.e Heading = Whip the eggs | ingredients,weight,measurement | 2 eggs,100g,1 cup
– HennyH
Apr 22 '13 at 11:54
@HennyH looking at Ashley's previous questions, he hasn't engaged in the slightest after dumping a question on the community. Not the best way to learn methinks.
– Henry Gomersall
Apr 22 '13 at 12:00
Unfortunately, I have to resort to putting most errors or issues I have with programming, on to forum websites for extra support, as the teacher who is supervising the controlled assessment doesn't know Python very well, and I can't ask any other teachers as it is a controlled assessment.
– Ashley Collinge
Apr 22 '13 at 15:55
|
show 15 more comments
Just to say, kudos for firstly learning proper skills in GCSE computing, and secondly for coming to a great place to learn it!
– Henry Gomersall
Apr 22 '13 at 11:32
1
Is there a formatting error in your code as presented?getColumn
doesn't appear to ever be called from outside of itself (which seems a strange thing in itself).
– Henry Gomersall
Apr 22 '13 at 11:48
Could you please explain the semantics behind "Recipe As" and the "headingX". My understanding is that heading would be the step and then the ingredients and their proportaions are listed underneat. I.e Heading = Whip the eggs | ingredients,weight,measurement | 2 eggs,100g,1 cup
– HennyH
Apr 22 '13 at 11:54
@HennyH looking at Ashley's previous questions, he hasn't engaged in the slightest after dumping a question on the community. Not the best way to learn methinks.
– Henry Gomersall
Apr 22 '13 at 12:00
Unfortunately, I have to resort to putting most errors or issues I have with programming, on to forum websites for extra support, as the teacher who is supervising the controlled assessment doesn't know Python very well, and I can't ask any other teachers as it is a controlled assessment.
– Ashley Collinge
Apr 22 '13 at 15:55
Just to say, kudos for firstly learning proper skills in GCSE computing, and secondly for coming to a great place to learn it!
– Henry Gomersall
Apr 22 '13 at 11:32
Just to say, kudos for firstly learning proper skills in GCSE computing, and secondly for coming to a great place to learn it!
– Henry Gomersall
Apr 22 '13 at 11:32
1
1
Is there a formatting error in your code as presented?
getColumn
doesn't appear to ever be called from outside of itself (which seems a strange thing in itself).– Henry Gomersall
Apr 22 '13 at 11:48
Is there a formatting error in your code as presented?
getColumn
doesn't appear to ever be called from outside of itself (which seems a strange thing in itself).– Henry Gomersall
Apr 22 '13 at 11:48
Could you please explain the semantics behind "Recipe As" and the "headingX". My understanding is that heading would be the step and then the ingredients and their proportaions are listed underneat. I.e Heading = Whip the eggs | ingredients,weight,measurement | 2 eggs,100g,1 cup
– HennyH
Apr 22 '13 at 11:54
Could you please explain the semantics behind "Recipe As" and the "headingX". My understanding is that heading would be the step and then the ingredients and their proportaions are listed underneat. I.e Heading = Whip the eggs | ingredients,weight,measurement | 2 eggs,100g,1 cup
– HennyH
Apr 22 '13 at 11:54
@HennyH looking at Ashley's previous questions, he hasn't engaged in the slightest after dumping a question on the community. Not the best way to learn methinks.
– Henry Gomersall
Apr 22 '13 at 12:00
@HennyH looking at Ashley's previous questions, he hasn't engaged in the slightest after dumping a question on the community. Not the best way to learn methinks.
– Henry Gomersall
Apr 22 '13 at 12:00
Unfortunately, I have to resort to putting most errors or issues I have with programming, on to forum websites for extra support, as the teacher who is supervising the controlled assessment doesn't know Python very well, and I can't ask any other teachers as it is a controlled assessment.
– Ashley Collinge
Apr 22 '13 at 15:55
Unfortunately, I have to resort to putting most errors or issues I have with programming, on to forum websites for extra support, as the teacher who is supervising the controlled assessment doesn't know Python very well, and I can't ask any other teachers as it is a controlled assessment.
– Ashley Collinge
Apr 22 '13 at 15:55
|
show 15 more comments
1 Answer
1
active
oldest
votes
up vote
0
down vote
This is a rewritten version of your program up above. The only thing that does not work is adding recipes. If you need further help, please post a comment on this answer to that effect. You will need to create a subdirectory alongside this program called recipes (or whatever you set the SUBDIR
variable name to be). To test, make sure you put your raspberry_pie.txt
file in that folder before running.
#-------------------------------------------------------------------------------
# Name: Recipe Holder
# Purpose: Hold recipes
#
# Author: Ashley Collinge & Stephen Chappell
#
# Created: 11 July 2013
# Copyright: (c) Ashley Collinge 2013
#-------------------------------------------------------------------------------
from collections import OrderedDict
from itertools import takewhile, zip_longest
from os import listdir, remove
from os.path import join, isfile, splitext, basename
#-------------------------------------------------------------------------------
SUBDIR = 'recipes'
def main():
print('Recipe Holder')
print('Use the numbers to navigate the menu.')
options = '1': view_recipe,
'2': add_recipe,
'3': delete_recipe
for key in sorted(options, key=int):
print(') '.format(key, get_title(options[key].__name__)))
while True:
choice = input('> ')
if choice in options:
options[choice]()
break
#-------------------------------------------------------------------------------
def view_recipe():
path = get_file('Type in the number of the recipe you '
'would like to view and press enter.')
print('Reciple for', get_name(path))
with open(path) as file:
lines = filter(None, map(str.strip, file))
for step in enumerate(takewhile('heading1'.__ne__, lines), 1):
print('. '.format(*step))
columns = OrderedDict((name.strip(), )
for name in next(lines).split(','))
max_split = len(columns) - 1
for info in takewhile('heading2'.__ne__, lines):
fields = tuple(map(str.strip, info.split(',', max_split)))
for key, value in zip_longest(columns, fields, fillvalue=''):
columns[key].append(value)
ingredients = columns['ingredients']
weights = columns['weight']
measurements = columns['measurement']
assert len(ingredients) == len(weights) == len(measurements)
print('Ingredients')
for specification in zip(ingredients, weights, measurements):
print(*specification)
def add_recipe():
raise NotImplementedError()
def delete_recipe():
path = get_file('Type in the number of the recipe you '
'would like to delete and press enter.')
remove(path)
#-------------------------------------------------------------------------------
def get_file(prompt):
files = tuple(name for name in
(join(SUBDIR, name) for name in listdir(SUBDIR))
if isfile(name))
for index, path in enumerate(files, 1):
print(') '.format(index, get_name(path)))
print('Type in the number of the recipe you '
'would like to view and press enter.')
return files[int(input('> ')) - 1]
def get_name(path):
return get_title(splitext(basename(path))[0])
def get_title(name):
return name.replace('_', ' ').title()
#-------------------------------------------------------------------------------
if __name__ == '__main__':
main()
add a comment |
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
0
down vote
This is a rewritten version of your program up above. The only thing that does not work is adding recipes. If you need further help, please post a comment on this answer to that effect. You will need to create a subdirectory alongside this program called recipes (or whatever you set the SUBDIR
variable name to be). To test, make sure you put your raspberry_pie.txt
file in that folder before running.
#-------------------------------------------------------------------------------
# Name: Recipe Holder
# Purpose: Hold recipes
#
# Author: Ashley Collinge & Stephen Chappell
#
# Created: 11 July 2013
# Copyright: (c) Ashley Collinge 2013
#-------------------------------------------------------------------------------
from collections import OrderedDict
from itertools import takewhile, zip_longest
from os import listdir, remove
from os.path import join, isfile, splitext, basename
#-------------------------------------------------------------------------------
SUBDIR = 'recipes'
def main():
print('Recipe Holder')
print('Use the numbers to navigate the menu.')
options = '1': view_recipe,
'2': add_recipe,
'3': delete_recipe
for key in sorted(options, key=int):
print(') '.format(key, get_title(options[key].__name__)))
while True:
choice = input('> ')
if choice in options:
options[choice]()
break
#-------------------------------------------------------------------------------
def view_recipe():
path = get_file('Type in the number of the recipe you '
'would like to view and press enter.')
print('Reciple for', get_name(path))
with open(path) as file:
lines = filter(None, map(str.strip, file))
for step in enumerate(takewhile('heading1'.__ne__, lines), 1):
print('. '.format(*step))
columns = OrderedDict((name.strip(), )
for name in next(lines).split(','))
max_split = len(columns) - 1
for info in takewhile('heading2'.__ne__, lines):
fields = tuple(map(str.strip, info.split(',', max_split)))
for key, value in zip_longest(columns, fields, fillvalue=''):
columns[key].append(value)
ingredients = columns['ingredients']
weights = columns['weight']
measurements = columns['measurement']
assert len(ingredients) == len(weights) == len(measurements)
print('Ingredients')
for specification in zip(ingredients, weights, measurements):
print(*specification)
def add_recipe():
raise NotImplementedError()
def delete_recipe():
path = get_file('Type in the number of the recipe you '
'would like to delete and press enter.')
remove(path)
#-------------------------------------------------------------------------------
def get_file(prompt):
files = tuple(name for name in
(join(SUBDIR, name) for name in listdir(SUBDIR))
if isfile(name))
for index, path in enumerate(files, 1):
print(') '.format(index, get_name(path)))
print('Type in the number of the recipe you '
'would like to view and press enter.')
return files[int(input('> ')) - 1]
def get_name(path):
return get_title(splitext(basename(path))[0])
def get_title(name):
return name.replace('_', ' ').title()
#-------------------------------------------------------------------------------
if __name__ == '__main__':
main()
add a comment |
up vote
0
down vote
This is a rewritten version of your program up above. The only thing that does not work is adding recipes. If you need further help, please post a comment on this answer to that effect. You will need to create a subdirectory alongside this program called recipes (or whatever you set the SUBDIR
variable name to be). To test, make sure you put your raspberry_pie.txt
file in that folder before running.
#-------------------------------------------------------------------------------
# Name: Recipe Holder
# Purpose: Hold recipes
#
# Author: Ashley Collinge & Stephen Chappell
#
# Created: 11 July 2013
# Copyright: (c) Ashley Collinge 2013
#-------------------------------------------------------------------------------
from collections import OrderedDict
from itertools import takewhile, zip_longest
from os import listdir, remove
from os.path import join, isfile, splitext, basename
#-------------------------------------------------------------------------------
SUBDIR = 'recipes'
def main():
print('Recipe Holder')
print('Use the numbers to navigate the menu.')
options = '1': view_recipe,
'2': add_recipe,
'3': delete_recipe
for key in sorted(options, key=int):
print(') '.format(key, get_title(options[key].__name__)))
while True:
choice = input('> ')
if choice in options:
options[choice]()
break
#-------------------------------------------------------------------------------
def view_recipe():
path = get_file('Type in the number of the recipe you '
'would like to view and press enter.')
print('Reciple for', get_name(path))
with open(path) as file:
lines = filter(None, map(str.strip, file))
for step in enumerate(takewhile('heading1'.__ne__, lines), 1):
print('. '.format(*step))
columns = OrderedDict((name.strip(), )
for name in next(lines).split(','))
max_split = len(columns) - 1
for info in takewhile('heading2'.__ne__, lines):
fields = tuple(map(str.strip, info.split(',', max_split)))
for key, value in zip_longest(columns, fields, fillvalue=''):
columns[key].append(value)
ingredients = columns['ingredients']
weights = columns['weight']
measurements = columns['measurement']
assert len(ingredients) == len(weights) == len(measurements)
print('Ingredients')
for specification in zip(ingredients, weights, measurements):
print(*specification)
def add_recipe():
raise NotImplementedError()
def delete_recipe():
path = get_file('Type in the number of the recipe you '
'would like to delete and press enter.')
remove(path)
#-------------------------------------------------------------------------------
def get_file(prompt):
files = tuple(name for name in
(join(SUBDIR, name) for name in listdir(SUBDIR))
if isfile(name))
for index, path in enumerate(files, 1):
print(') '.format(index, get_name(path)))
print('Type in the number of the recipe you '
'would like to view and press enter.')
return files[int(input('> ')) - 1]
def get_name(path):
return get_title(splitext(basename(path))[0])
def get_title(name):
return name.replace('_', ' ').title()
#-------------------------------------------------------------------------------
if __name__ == '__main__':
main()
add a comment |
up vote
0
down vote
up vote
0
down vote
This is a rewritten version of your program up above. The only thing that does not work is adding recipes. If you need further help, please post a comment on this answer to that effect. You will need to create a subdirectory alongside this program called recipes (or whatever you set the SUBDIR
variable name to be). To test, make sure you put your raspberry_pie.txt
file in that folder before running.
#-------------------------------------------------------------------------------
# Name: Recipe Holder
# Purpose: Hold recipes
#
# Author: Ashley Collinge & Stephen Chappell
#
# Created: 11 July 2013
# Copyright: (c) Ashley Collinge 2013
#-------------------------------------------------------------------------------
from collections import OrderedDict
from itertools import takewhile, zip_longest
from os import listdir, remove
from os.path import join, isfile, splitext, basename
#-------------------------------------------------------------------------------
SUBDIR = 'recipes'
def main():
print('Recipe Holder')
print('Use the numbers to navigate the menu.')
options = '1': view_recipe,
'2': add_recipe,
'3': delete_recipe
for key in sorted(options, key=int):
print(') '.format(key, get_title(options[key].__name__)))
while True:
choice = input('> ')
if choice in options:
options[choice]()
break
#-------------------------------------------------------------------------------
def view_recipe():
path = get_file('Type in the number of the recipe you '
'would like to view and press enter.')
print('Reciple for', get_name(path))
with open(path) as file:
lines = filter(None, map(str.strip, file))
for step in enumerate(takewhile('heading1'.__ne__, lines), 1):
print('. '.format(*step))
columns = OrderedDict((name.strip(), )
for name in next(lines).split(','))
max_split = len(columns) - 1
for info in takewhile('heading2'.__ne__, lines):
fields = tuple(map(str.strip, info.split(',', max_split)))
for key, value in zip_longest(columns, fields, fillvalue=''):
columns[key].append(value)
ingredients = columns['ingredients']
weights = columns['weight']
measurements = columns['measurement']
assert len(ingredients) == len(weights) == len(measurements)
print('Ingredients')
for specification in zip(ingredients, weights, measurements):
print(*specification)
def add_recipe():
raise NotImplementedError()
def delete_recipe():
path = get_file('Type in the number of the recipe you '
'would like to delete and press enter.')
remove(path)
#-------------------------------------------------------------------------------
def get_file(prompt):
files = tuple(name for name in
(join(SUBDIR, name) for name in listdir(SUBDIR))
if isfile(name))
for index, path in enumerate(files, 1):
print(') '.format(index, get_name(path)))
print('Type in the number of the recipe you '
'would like to view and press enter.')
return files[int(input('> ')) - 1]
def get_name(path):
return get_title(splitext(basename(path))[0])
def get_title(name):
return name.replace('_', ' ').title()
#-------------------------------------------------------------------------------
if __name__ == '__main__':
main()
This is a rewritten version of your program up above. The only thing that does not work is adding recipes. If you need further help, please post a comment on this answer to that effect. You will need to create a subdirectory alongside this program called recipes (or whatever you set the SUBDIR
variable name to be). To test, make sure you put your raspberry_pie.txt
file in that folder before running.
#-------------------------------------------------------------------------------
# Name: Recipe Holder
# Purpose: Hold recipes
#
# Author: Ashley Collinge & Stephen Chappell
#
# Created: 11 July 2013
# Copyright: (c) Ashley Collinge 2013
#-------------------------------------------------------------------------------
from collections import OrderedDict
from itertools import takewhile, zip_longest
from os import listdir, remove
from os.path import join, isfile, splitext, basename
#-------------------------------------------------------------------------------
SUBDIR = 'recipes'
def main():
print('Recipe Holder')
print('Use the numbers to navigate the menu.')
options = '1': view_recipe,
'2': add_recipe,
'3': delete_recipe
for key in sorted(options, key=int):
print(') '.format(key, get_title(options[key].__name__)))
while True:
choice = input('> ')
if choice in options:
options[choice]()
break
#-------------------------------------------------------------------------------
def view_recipe():
path = get_file('Type in the number of the recipe you '
'would like to view and press enter.')
print('Reciple for', get_name(path))
with open(path) as file:
lines = filter(None, map(str.strip, file))
for step in enumerate(takewhile('heading1'.__ne__, lines), 1):
print('. '.format(*step))
columns = OrderedDict((name.strip(), )
for name in next(lines).split(','))
max_split = len(columns) - 1
for info in takewhile('heading2'.__ne__, lines):
fields = tuple(map(str.strip, info.split(',', max_split)))
for key, value in zip_longest(columns, fields, fillvalue=''):
columns[key].append(value)
ingredients = columns['ingredients']
weights = columns['weight']
measurements = columns['measurement']
assert len(ingredients) == len(weights) == len(measurements)
print('Ingredients')
for specification in zip(ingredients, weights, measurements):
print(*specification)
def add_recipe():
raise NotImplementedError()
def delete_recipe():
path = get_file('Type in the number of the recipe you '
'would like to delete and press enter.')
remove(path)
#-------------------------------------------------------------------------------
def get_file(prompt):
files = tuple(name for name in
(join(SUBDIR, name) for name in listdir(SUBDIR))
if isfile(name))
for index, path in enumerate(files, 1):
print(') '.format(index, get_name(path)))
print('Type in the number of the recipe you '
'would like to view and press enter.')
return files[int(input('> ')) - 1]
def get_name(path):
return get_title(splitext(basename(path))[0])
def get_title(name):
return name.replace('_', ' ').title()
#-------------------------------------------------------------------------------
if __name__ == '__main__':
main()
answered Jul 11 '13 at 15:03
Noctis Skytower
13.2k115688
13.2k115688
add a comment |
add a comment |
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f16146075%2fpython-recipe-program%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Just to say, kudos for firstly learning proper skills in GCSE computing, and secondly for coming to a great place to learn it!
– Henry Gomersall
Apr 22 '13 at 11:32
1
Is there a formatting error in your code as presented?
getColumn
doesn't appear to ever be called from outside of itself (which seems a strange thing in itself).– Henry Gomersall
Apr 22 '13 at 11:48
Could you please explain the semantics behind "Recipe As" and the "headingX". My understanding is that heading would be the step and then the ingredients and their proportaions are listed underneat. I.e Heading = Whip the eggs | ingredients,weight,measurement | 2 eggs,100g,1 cup
– HennyH
Apr 22 '13 at 11:54
@HennyH looking at Ashley's previous questions, he hasn't engaged in the slightest after dumping a question on the community. Not the best way to learn methinks.
– Henry Gomersall
Apr 22 '13 at 12:00
Unfortunately, I have to resort to putting most errors or issues I have with programming, on to forum websites for extra support, as the teacher who is supervising the controlled assessment doesn't know Python very well, and I can't ask any other teachers as it is a controlled assessment.
– Ashley Collinge
Apr 22 '13 at 15:55