0

Say I have a text file with recipes fomatted like this:

TITLE: Michigan Pie:

INGREDIENTS: 8 oz cream cheese 1 can sweetened, condensed milk ¼ c lemon juice 15 oz crushed pineapple 8 oz whipped cream

DIRECTIONS: Drain the pineapple very well. Beat the cream cheese until it’s very smooth. Add the sweetened, condensed milk a little bit at a time. Mix in the lemon juice and pineapple. Fold in the whipped cream. Pour the mixture into two graham cracker pie crusts and refrigerate.

how could I use Python to sort all the titles together, all the ingredients together etc...??

2
  • when i looked at this my first thought was: kragen's aislesort.py but that requires the file's records to be blank line separated, and it needs a regex to extract what to sort by. Commented Nov 26, 2011 at 22:05
  • This is remarkably close to stackoverflow.com/questions/8280533/… . Please read tinyurl.com/so-hints and work on improving existing questions rather than pose them as new questions. Commented Nov 27, 2011 at 6:23

3 Answers 3

1

Initialize a dictionary with three keys: TITLE, INGREDIENTS, DIRECTIONS.

Parse the text file. Whenever you find one of the keys, add the text below it to the appropriate key value pair in the dictionary. Stop when you see another bold faced key and continue parsing.

If you would prefer a list of the TITLES, for example, instead of just a long, long, long string, use a dictionary that holds a list.

e.g.

data = {'TITLE':[], 'INGREDIENTS':[], 'DIRECTIONS':[]}

Append parsed data into list.

Sign up to request clarification or add additional context in comments.

2 Comments

i like your answer but how would I print from the key to the next key?
Iterate over the dictionary (like you would a list) to get access to the keys one at a time.
0

1) Load all files, parse them and put then into a list of dictionnaries

2) Sort the list the way you want (see How do I sort a list of dictionaries by values of the dictionary in Python? )

Comments

0

Assuming the list of recipes is in recipe.txt and that the header is always separated with a colon, the following code gets you your dictionary.

with open('recipe.txt') as recipe:
  g = ( line.split(':',1) for line in recipe )
  g = ( (i[0],i[1:]) for i in g if len(i)>1 )
  d = dict()
  for k,v in b:
    d[k] = d.get(k,[]) + v

Now just sort it however you'd like.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.