-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.py
81 lines (63 loc) · 1.9 KB
/
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
import urlparse
import urllib
import nutrition
from bs4 import BeautifulSoup
def create_food(url):
try:
htmltext = urllib.urlopen(url).read()
except:
print("Error!")
print(url)
soup = BeautifulSoup(htmltext)
strings = []
#gives you beautifulsoup strings
for text in soup.stripped_strings:
strings.append(text)
name = soup.find("form").get_text(strip=True) # gets the name
name.encode()
fatn, fatp, carbn, carbp, protn, protp = 0, 0, 0, 0, 0, 0
fat = []
carb = []
cholesterol = []
sodium = []
protein = []
"""
Parses for fat, carbs, protein
"""
for i in range(len(strings)):
if strings[i] == "Total Fat":
food = strings[i] + " " + strings[i + 1] + " " + strings[i+2] + strings[i+3]
fat.append(food.encode('utf-8'))
fatn = strings[i + 1]
fatp = strings[i+2]
if strings[i] == "Tot. Carb.":
food = strings[i] + " " + strings[i + 1] + " " + strings[i+2] + strings[i+3]
carb.append(food.encode('utf-8'))
carbn = strings[i + 1]
carbp = strings[i+2]
if strings[i] == "Cholesterol":
food = strings[i] + " " + strings[i + 1] + " " + strings[i+2] + strings[i+3]
cholesterol.append(food.encode('utf-8'))
if strings[i] == "Sodium":
food = strings[i] + " " + strings[i + 1] + " " + strings[i+2] + strings[i+3]
sodium.append(food.encode('utf-8'))
if strings[i] == "Protein":
food = strings[i] + " " + strings[i + 1]
protein.append(food.encode('utf-8'))
protn = strings[i + 1]
"""
parses for Calories
"""
gen = (line for line in soup.stripped_strings if "Calories" in line)
calo = ""
for line in gen:
if not "Fat" in line:
calo = line.strip()
calo = ''.join([i for i in calo if i.isdigit()])
#calo = int(calo)
#else:
# fat = line.strip()
# fat = ''.join([i for i in calo if i.isdigit()])
nut = nutrition.Food(name, fatn, fatp, carbn, carbp, protn, calo)
#creates a Food object that contains floats denoting fat, carbs, etc.
return nut