自动补全与输入联想功能已经是大多数网站的标配,给表单加入自动补全功能大大节省了用户输入时间,而输入联想功能则起到了预测用户喜好的作用,两个功能都是提升用户体验的利器。
本实训,我们通过实现搜索历史、自动补全和搜索预测三大常用功能,带领大家编写实用的程序组件。
搜索历史功能
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import redis
conn = redis.Redis()
# 将最新搜索词记录到搜索记录列表中
def add_search_history(user_id, keyword):
# 请在下面完成要求的功能
#********* Begin *********#
history_list = "recent:search:"+user_id
pipe = conn.pipeline()
pipe.multi()
pipe.lrem(history_list, keyword)
pipe.lpush(history_list, keyword)
pipe.ltrim(history_list, 0, 49)
pipe.execute()
#********* End *********#
# 删除搜索记录列表中的指定搜索词
def remove_search_history(user_id, keyword):
# 请在下面完成要求的功能
#********* Begin *********#
conn.lrem("recent:search:"+ user_id, keyword)
#********* End *********#
# 获取到自动匹配的搜索词列表
def fetch_autocomplete_list(user_id, prefix):
# 请在下面完成要求的功能
#********* Begin *********#
candidates = conn.lrange("recent:search:" + user_id, 0, -1)
matches = []
for candidate in candidates:
if candidate.startswith(prefix):
matches.append(candidate)
return matches
#********* End *********#
自动补全功能
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import uuid
import redis
import bisect
conn = redis.Redis()
# 生成起始元素和结束元素
def find_prefix_range(prefix):
# 请在下面完成要求的功能
#********* Begin *********#
characters = "`abcdefghijklmnopqrstuvwxyz{"
posn = bisect.bisect_left(characters, prefix[-1:])
suffix = characters[(posn or 1) - 1]
return prefix[:-1] + suffix + '{', prefix + '{'
#********* End *********#
# 获取匹配提示词列表
def autocomplete_on_prefix(prefix):
# 请在下面完成要求的功能
#********* Begin *********#
zset_name = 'autocomplete:candidates'
start, end = find_prefix_range(prefix)
identifier = str(uuid.uuid4())
start += identifier
end += identifier
conn.zadd(zset_name, start, 0, end, 0)
sindex = conn.zrank(zset_name, start)
eindex = conn.zrank(zset_name, end)
erange = min(sindex + 9, eindex - 2)
pipe = conn.pipeline()
pipe.multi()
pipe.zrem(zset_name, start, end)
pipe.zrange(zset_name, sindex, erange)
items = pipe.execute()[-1]
#********* End *********#
return [item for item in items if '{' not in item]
搜索预测功能
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import redis
conn = redis.Redis()
# 记录搜索词频次
def add_keyword_frequency(keyword):
# 请在下面完成要求的功能
#********* Begin *********#
for i in xrange(len(keyword)):
zset_name = "keyword:"+keyword[0:i+1]
conn.zincrby(zset_name, keyword, 1)
conn.zremrangebyrank(zset_name, 20, -1)
conn.expire(zset_name, 86400)
#********* End *********#
# 获取搜索预测列表
def get_search_suggestions(prefix):
# 请在下面完成要求的功能
#********* Begin *********#
return conn.zrevrange("keyword:" + prefix, 0, -1)
#********* End *********#
感谢大家的支持!!!