-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathtokenize_recipes.py
More file actions
71 lines (56 loc) · 1.98 KB
/
Copy pathtokenize_recipes.py
File metadata and controls
71 lines (56 loc) · 1.98 KB
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
"""Tokenize recipes."""
import _pickle as pickle
from os import path
from nltk.tokenize import word_tokenize
from nltk import download
from tqdm import tqdm
import config
import prep_data
from parse_ingredients import parse_ingredient_list
def tokenize_sentence(sentence):
"""Tokenize a sentence."""
try:
return ' '.join(list(filter(
lambda x: x.lower() != "advertisement",
word_tokenize(sentence))))
except LookupError:
print('Downloading NLTK data')
download()
return ' '.join(list(filter(
lambda x: x.lower() != "advertisement",
word_tokenize(sentence))))
def recipe_is_complete(r):
"""Return True if recipe is complete and False otherwise.
Completeness is defined as the recipe containing a title and instructions.
"""
if ('title' not in r) or ('instructions' not in r):
return False
if (r['title'] is None) or (r['instructions'] is None):
return False
return True
def tokenize_recipes(recipes):
"""Tokenise all recipes."""
tokenized = []
for r in tqdm(recipes.values()):
if recipe_is_complete(r):
ingredients = '; '.join(parse_ingredient_list(r['ingredients'])) + '; '
tokenized.append((
tokenize_sentence(r['title']),
tokenize_sentence(ingredients) + tokenize_sentence(r['instructions'])))
return tuple(map(list, zip(*tokenized)))
def pickle_recipes(recipes):
"""Pickle all recipe tokens to disk."""
with open(path.join(config.path_data, 'tokens.pkl'), 'wb') as f:
pickle.dump(recipes, f, 2)
def load_recipes():
"""Read pickled recipe tokens from disk."""
with open(path.join(config.path_data, 'tokens.pkl'), 'rb') as f:
recipes = pickle.load(f)
return recipes
def main():
"""Tokenize recipes."""
recipes = prep_data.load_recipes()
text_sum_data = tokenize_recipes(recipes)
pickle_recipes(text_sum_data)
if __name__ == '__main__':
main()