-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathingredient_parser.py
483 lines (467 loc) · 10.6 KB
/
ingredient_parser.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
# /Users/Jack/Documents/Projects/Whatscooking-/src
import pandas as pd
import nltk
import string
import ast
import re
import unidecode
# nltk.download('wordnet')
from nltk.stem import WordNetLemmatizer
from nltk.corpus import wordnet
from collections import Counter
# import config
# Weigths and measures are words that will not add value to the model. I got these standard words from
# https://en.wikibooks.org/wiki/Cookbook:Units_of_measurement
# # We lemmatize the words to reduce them to their smallest form (lemmas).
# lemmatizer = WordNetLemmatizer()
# measures = [lemmatizer.lemmatize(m) for m in measures]
# words_to_remove = [lemmatizer.lemmatize(m) for m in words_to_remove]
def ingredient_parser(ingreds):
"""
This function takes in a list (but it is a string as it comes from pandas dataframe) of
ingredients and performs some preprocessing.
For example:
input = '['1 x 1.6kg whole duck', '2 heaped teaspoons Chinese five-spice powder', '1 clementine',
'6 fresh bay leaves', 'GRAVY', '', '1 bulb of garlic', '2 carrots', '2 red onions',
'3 tablespoons plain flour', '100 ml Marsala', '1 litre organic chicken stock']'
output = ['duck', 'chinese five spice powder', 'clementine', 'fresh bay leaf', 'gravy', 'garlic',
'carrot', 'red onion', 'plain flour', 'marsala', 'organic chicken stock']
"""
measures = [
"teaspoon",
"t",
"tsp.",
"tablespoon",
"T",
"tbl.",
"tb",
"tbsp.",
"fluid ounce",
"fl oz",
"gill",
"cup",
"c",
"pint",
"p",
"pt",
"fl pt",
"quart",
"q",
"qt",
"fl qt",
"gallon",
"g",
"gal",
"ml",
"milliliter",
"millilitre",
"cc",
"mL",
"l",
"liter",
"litre",
"L",
"dl",
"deciliter",
"decilitre",
"dL",
"bulb",
"level",
"heaped",
"rounded",
"whole",
"pinch",
"medium",
"slice",
"pound",
"lb",
"#",
"ounce",
"oz",
"mg",
"milligram",
"milligramme",
"g",
"gram",
"gramme",
"kg",
"kilogram",
"kilogramme",
"x",
"of",
"mm",
"millimetre",
"millimeter",
"cm",
"centimeter",
"centimetre",
"m",
"meter",
"metre",
"inch",
"in",
"milli",
"centi",
"deci",
"hecto",
"kilo",
]
words_to_remove = [
"fresh",
"minced",
"chopped" "oil",
"a",
"red",
"bunch",
"and",
"clove",
"or",
"leaf",
"chilli",
"large",
"extra",
"sprig",
"ground",
"handful",
"free",
"small",
"virgin",
"range",
"from",
"dried",
"sustainable",
"black",
"peeled",
"higher",
"welfare",
"seed",
"for",
"finely",
"freshly",
"sea",
"quality",
"white",
"ripe",
"few",
"piece",
"source",
"to",
"organic",
"flat",
"smoked",
"ginger",
"sliced",
"green",
"picked",
"the",
"stick",
"plain",
"plus",
"mixed",
"mint",
"bay",
"basil",
"your",
"cumin",
"optional",
"fennel",
"serve",
"mustard",
"unsalted",
"baby",
"paprika",
"fat",
"ask",
"natural",
"skin",
"roughly",
"into",
"such",
"cut",
"good",
"brown",
"grated",
"trimmed",
"oregano",
"powder",
"yellow",
"dusting",
"knob",
"frozen",
"on",
"deseeded",
"low",
"runny",
"balsamic",
"cooked",
"streaky",
"nutmeg",
"sage",
"rasher",
"zest",
"pin",
"groundnut",
"breadcrumb",
"turmeric",
"halved",
"grating",
"stalk",
"light",
"tinned",
"dry",
"soft",
"rocket",
"bone",
"colour",
"washed",
"skinless",
"leftover",
"splash",
"removed",
"dijon",
"thick",
"big",
"hot",
"drained",
"sized",
"chestnut",
"watercress",
"fishmonger",
"english",
"dill",
"caper",
"raw",
"worcestershire",
"flake",
"cider",
"cayenne",
"tbsp",
"leg",
"pine",
"wild",
"if",
"fine",
"herb",
"almond",
"shoulder",
"cube",
"dressing",
"with",
"chunk",
"spice",
"thumb",
"garam",
"new",
"little",
"punnet",
"peppercorn",
"shelled",
"saffron",
"other" "chopped",
"salt",
"olive",
"taste",
"can",
"sauce",
"water",
"diced",
"package",
"italian",
"shredded",
"divided",
"parsley",
"vinegar",
"all",
"purpose",
"crushed",
"juice",
"more",
"coriander",
"bell",
"needed",
"thinly",
"boneless",
"half",
"thyme",
"cubed",
"cinnamon",
"cilantro",
"jar",
"seasoning",
"rosemary",
"extract",
"sweet",
"baking",
"beaten",
"heavy",
"seeded",
"tin",
"vanilla",
"uncooked",
"crumb",
"style",
"thin",
"nut",
"coarsely",
"spring",
"chili",
"cornstarch",
"strip",
"cardamom",
"rinsed",
"honey",
"cherry",
"root",
"quartered",
"head",
"softened",
"container",
"crumbled",
"frying",
"lean",
"cooking",
"roasted",
"warm",
"whipping",
"thawed",
"corn",
"pitted",
"sun",
"kosher",
"bite",
"toasted",
"lasagna",
"split",
"melted",
"degree",
"lengthwise",
"romano",
"packed",
"pod",
"anchovy",
"rom",
"prepared",
"juiced",
"fluid",
"floret",
"room",
"active",
"seasoned",
"mix",
"deveined",
"lightly",
"anise",
"thai",
"size",
"unsweetened",
"torn",
"wedge",
"sour",
"basmati",
"marinara",
"dark",
"temperature",
"garnish",
"bouillon",
"loaf",
"shell",
"reggiano",
"canola",
"parmigiano",
"round",
"canned",
"ghee",
"crust",
"long",
"broken",
"ketchup",
"bulk",
"cleaned",
"condensed",
"sherry",
"provolone",
"cold",
"soda",
"cottage",
"spray",
"tamarind",
"pecorino",
"shortening",
"part",
"bottle",
"sodium",
"cocoa",
"grain",
"french",
"roast",
"stem",
"link",
"firm",
"asafoetida",
"mild",
"dash",
"boiling",
"oil",
"chopped",
"vegetable oil",
"chopped oil",
"garlic",
"skin off",
"bone out" "from sustrainable sources",
]
# The ingredient list is now a string so we need to turn it back into a list. We use ast.literal_eval
if isinstance(ingreds, list):
ingredients = ingreds
else:
ingredients = ast.literal_eval(ingreds)
# We first get rid of all the punctuation. We make use of str.maketrans. It takes three input
# arguments 'x', 'y', 'z'. 'x' and 'y' must be equal-length strings and characters in 'x'
# are replaced by characters in 'y'. 'z' is a string (string.punctuation here) where each character
# in the string is mapped to None.
translator = str.maketrans("", "", string.punctuation)
lemmatizer = WordNetLemmatizer()
ingred_list = []
for i in ingredients:
i.translate(translator)
# We split up with hyphens as well as spaces
items = re.split(" |-", i)
# Get rid of words containing non alphabet letters
items = [word for word in items if word.isalpha()]
# Turn everything to lowercase
items = [word.lower() for word in items]
# remove accents
items = [
unidecode.unidecode(word) for word in items
] #''.join((c for c in unicodedata.normalize('NFD', items) if unicodedata.category(c) != 'Mn'))
# Lemmatize words so we can compare words to measuring words
items = [lemmatizer.lemmatize(word) for word in items]
# Gets rid of measuring words/phrases, e.g. heaped teaspoon
items = [word for word in items if word not in measures]
# Get rid of common easy words
items = [word for word in items if word not in words_to_remove]
if items:
ingred_list.append(" ".join(items))
# ingred_list = " ".join(ingred_list)
return ingred_list
if __name__ == "__main__":
recipe_df = pd.read_csv('recipes.csv')
recipe_df["ingredients_parsed"] = recipe_df["ingredients"].apply(
lambda x: ingredient_parser(x)
)
df = recipe_df[["recipe_name", "ingredients_parsed", "ingredients", "recipe_urls"]]
df = recipe_df.dropna()
# remove - Allrecipes.com from end of every recipe title
m = df.recipe_name.str.endswith("Recipe - Allrecipes.com")
df["recipe_name"].loc[m] = df.recipe_name.loc[m].str[:-23]
df.to_csv('df_parsed.csv', index=False)
# vocabulary = nltk.FreqDist()
# for ingredients in recipe_df['ingredients']:
# ingredients = ingredients.split()
# vocabulary.update(ingredients)
# for word, frequency in vocabulary.most_common(200):
# print(f'{word};{frequency}')
# fdist = nltk.FreqDist(ingredients)
# common_words = []
# for word, _ in vocabulary.most_common(250):
# common_words.append(word)
# print(common_words)