diff options
author | Ben Cohen <ben@kensho.com> | 2019-07-28 19:54:44 -0400 |
---|---|---|
committer | Ben Cohen <ben@kensho.com> | 2019-07-28 19:54:44 -0400 |
commit | 88c2dc94bba23097e2a573b294dd7e585644d58e (patch) | |
tree | f56244379b15a237341f1da945b98144821738a8 | |
parent | 0c6d39354b86626badf6b6e11c14935833cb009d (diff) |
search!
-rw-r--r-- | app.py | 36 |
1 files changed, 32 insertions, 4 deletions
@@ -1,9 +1,11 @@ from flask import Flask, render_template, redirect, request, url_for, jsonify from utils import get_closest, translate_to_attr, get_style_preds, translate_to_style import json +import string import random import re from utils import get_drinks_like +from collections import defaultdict app = Flask(__name__) @@ -12,7 +14,14 @@ with open("./data/beer_info_small.json") as beers_json: # beer_ids = {} # for long_id, val in beer.items(): # beer_ids[val[0]] = long_id.split('-')[1] +with open('./data/name_list.json') as f: + name_list = json.load(f) + +orig_terms = list(name_list.keys()) + +search_words = [''.join(f for f in x.lower() if f not in string.punctuation) for x in orig_terms] +orig_term_map = dict(zip(search_words, orig_terms)) beers_for_random = [b for b in beer if beer[b][3] > 75] @@ -23,8 +32,7 @@ with open('./data/brewery_names.json') as f: # for id, name in brewery_names.items(): # brewery_ids[name] = id -with open('./data/name_list.json') as f: - name_list = json.load(f) + ATTRS = ['Barnyardy', 'Bitter', @@ -115,8 +123,12 @@ def get_beer_details(brewery_id, beer_id): @app.route('/all_beers.json') def get_all_beers(): - names = [brewery_names[k.split('-')[0]]+' — '+v[0] for k, v in beer.items()] - return jsonify(names[0:20]) + q = request.args.get('q') + if not q: + return redirect('/') + + return jsonify([orig_term_map[x] for x in search(q)]) + # return jsonify(names[0:20]) @app.route('/search', methods=['POST']) def search(): @@ -129,6 +141,22 @@ def search(): return redirect(url_for('get_beer_details', beer_id=beer_id, brewery_id=brewery_id)) + +def search(query): + query = query.lower() + query = ''.join(x for x in query if x not in string.punctuation) + print(query) + split_query = query.split(' ') + all_matches = defaultdict(int) + for term in split_query: + matches = [x for x in search_words if term in x] +# print(matches) + for m in matches: + all_matches[m] += 1/len(matches) + + return sorted(all_matches, key=lambda x: all_matches[x], reverse=True)[:10] + + def beer_lookup(brewery_id, beer_id=None): if beer_id: item_id = brewery_id + "-" + beer_id |