feat:提交代码
This commit is contained in:
parent
c6ea6ca4ef
commit
930e27f305
10
cf3.py
10
cf3.py
@ -43,7 +43,7 @@ product_ratings_window = defaultdict(lambda: defaultdict(lambda: [0, 0]))
|
|||||||
|
|
||||||
def get_top_n_products(ratings_dict, n=3):
|
def get_top_n_products(ratings_dict, n=3):
|
||||||
rated_products = [
|
rated_products = [
|
||||||
(prod, total / cnt) for prod, (total, cnt) in ratings_dict.items()
|
(prod, total / cnt) for prod, (total, cnt) in ratings_dict.items()#用字典,剑是商品名,值是总评分,次数
|
||||||
]
|
]
|
||||||
rated_products.sort(key=lambda x: x[1], reverse=True)
|
rated_products.sort(key=lambda x: x[1], reverse=True)
|
||||||
return [p[0] for p in rated_products[:n]]
|
return [p[0] for p in rated_products[:n]]
|
||||||
@ -51,8 +51,8 @@ def get_top_n_products(ratings_dict, n=3):
|
|||||||
# =================== 插入 MySQL 函数
|
# =================== 插入 MySQL 函数
|
||||||
def insert_top_products_to_mysql(category, top_products_list, window_end_time):
|
def insert_top_products_to_mysql(category, top_products_list, window_end_time):
|
||||||
try:
|
try:
|
||||||
top_products_json = json.dumps(top_products_list, ensure_ascii=False)
|
top_products_json = json.dumps(top_products_list, ensure_ascii=False)#数据转换
|
||||||
timestamp = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(window_end_time))
|
timestamp = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(window_end_time))#热门商品列表(JSON 字符串)
|
||||||
query = """
|
query = """
|
||||||
INSERT INTO category_top_products (category, top_products, timestamp)
|
INSERT INTO category_top_products (category, top_products, timestamp)
|
||||||
VALUES (%s, %s, %s)
|
VALUES (%s, %s, %s)
|
||||||
@ -67,7 +67,7 @@ def insert_top_products_to_mysql(category, top_products_list, window_end_time):
|
|||||||
# =================== 主循环
|
# =================== 主循环
|
||||||
try:
|
try:
|
||||||
while True:
|
while True:
|
||||||
msg = consumer.poll(timeout=1.0)
|
msg = consumer.poll(timeout=1.0)#消息轮询
|
||||||
current_time = int(time.time())
|
current_time = int(time.time())
|
||||||
|
|
||||||
# 判断是否到了窗口结束时间
|
# 判断是否到了窗口结束时间
|
||||||
@ -76,7 +76,7 @@ try:
|
|||||||
|
|
||||||
# 为每个类别生成 Top 3 推荐
|
# 为每个类别生成 Top 3 推荐
|
||||||
for category, products in product_ratings_window.items():
|
for category, products in product_ratings_window.items():
|
||||||
top3 = get_top_n_products(products)
|
top3 = get_top_n_products(products)#热门商品
|
||||||
insert_top_products_to_mysql(category, top3, current_time)
|
insert_top_products_to_mysql(category, top3, current_time)
|
||||||
|
|
||||||
# 清空窗口缓存,更新窗口起始时间
|
# 清空窗口缓存,更新窗口起始时间
|
||||||
|
Loading…
x
Reference in New Issue
Block a user