-
Notifications
You must be signed in to change notification settings - Fork 1
/
search.py
63 lines (53 loc) · 1.32 KB
/
search.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
import sqlite3
import json
import sys
import parseIngredients
conn = sqlite3.connect('nutrients.db')
c = conn.cursor()
def get_nutrients(id):
c.execute("""
SELECT
name,
units,
amount
FROM nutrition
JOIN nutrient
JOIN common_nutrient
ON nutrition.food_id = ?
AND nutrition.nutrient_id = nutrient.id
AND nutrient.id = common_nutrient.id
""", (id,))
vals = {}
for row in c:
vals[row[0]] = str(row[2]) + ' ' + row[1]
return json.dumps(vals, sort_keys=True, indent=4)
def get_food_id(text):
search_clause = '%' + text + '%'
c.execute('SELECT id, long_desc FROM food WHERE long_desc LIKE ?', (search_clause,))
try:
item = get_simplest(c.fetchall())
except IndexError:
return "Not found!"
return item[0]
def get_food_name(text):
search_clause = '%' + text + '%'
c.execute('SELECT id, long_desc FROM food WHERE long_desc LIKE ?', (search_clause,))
try:
item = get_simplest(c.fetchall())
except IndexError:
return "Not found!"
return item[1]
def get_simplest(dlst):
x = len(dlst[0][1])
xk = 0
for i in range(0, len(dlst)):
if x < len(dlst[i][1]):
pass
else:
x = len(dlst[i][1])
xk = i
return dlst[xk]
def get_hits(text):
search_clause = '%' + text + '%'
c.execute('SELECT id, long_desc FROM food WHERE long_desc LIKE ?', (search_clause,))
return len(c.fetchall())