quantumdisaster
quantumdisaster

Reputation: 587

sorting text files with python

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...??

Upvotes: 0

Views: 295

Answers (3)

Kyle G
Kyle G

Reputation: 1038

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.

Upvotes: 0

Josh Imhoff
Josh Imhoff

Reputation: 6956

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.

Upvotes: 1

gecco
gecco

Reputation: 18850

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? )

Upvotes: 0

Related Questions