python实现关键词搜索

该项目使用Python从json文件中搜索菜谱,支持多关键词搜索并按相关性、健康度和简单度排序。搜索结果返回前十个相关菜谱,排序方式包括默认相关性排序、卡路里与营养健康度排序及原材料和步骤简洁度排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个项目是要从存储了许多菜谱的json文件中依据关键词快速找到相应菜谱。

使用时,直接使用search函数即可找相关菜谱,支持多个关键词搜索,支持高评分词条优先显示。搜索结果为前十个相关菜谱,显示时有三种排序方式:
ordering=‘normal’:默认排序,依照相关性。
ordering=‘health’:依据卡路里,蛋白质,脂肪数值计算菜谱是否健康,将更健康的排在前面。
ordering=‘simple’:依据原材料数量和烧菜步骤数量,将更简单的菜谱排在前面。

import json
import re
import sys
#有用到sys.maxsize,这是系统最大int型整数,方便排序

#parse and tokenize (split into words) of all recipes
def process_recipes(filename):
    #定义新的dictiorary数据库存储菜谱数据
    title_to_terms = {
   
   }
    categories_to_terms = {
   
   }
    ingredients_to_terms = {
   
   }
    directions_to_terms = {
   
   }
    pattern = re.compile('[\W_]+')
    
    #打开json文件
    with open(filename) as f:
        recipes = json.load(f)
        print(len(recipes))
        for recipe_number in range(20):
            #将每个菜谱句子分解成单词,存入词袋库(dictionary实现)
            recipe = recipes[recipe_number]
            recipe_to_terms[recipe_number] = {
   
   }
            
            #如果此recipe有title,将此title句子分割为一组单词并存入数据库
            if 'title' in recipe.keys():
                title = recipe['title']
                title_to_terms['title'] = pattern.sub(' ',title)
                re.sub(r'[\W_]+','', title_to_terms['title'])
                title_to_terms['title'] = title_to_terms['title'].split()
                recipe_to_terms[recipe_number].update(title_to_terms)
            #如果此recipe有categories,将此categories句子分割为一组单词并存入数据库 
            if 'categories' in recipe.keys():
                categories = str(recipe['categories'])
                categories_to_terms['categories'] = pattern.sub(' ',categories)
                re.sub(r'[\W_]+','', categories_to_terms['categories'])
                categories_to_terms['categories'] = categories_to_terms['categories'].split()
                recipe_to_terms[recipe_number].update(categories_to_terms)
            #如果此recipe有ingredients,统计原料数量存入数据库,将此ingredients句子分割为一组单词并存入数据库 
            if 'ingredients' in recipe.keys():
                recipe_to_terms[recipe_number].update({
   
   'number':len(recipe['ingredients'])})
                
                ingredients = str(recipe['ingredients'])
                ingredients_to_terms['ingredients'] = pattern.sub(' ',ingredients)
                re.sub(r'[\W_]+','', ingredients_to_terms['ingredients'])
                ingredients_to_terms['ingredients'] = ingredients_to_terms['ingredients'].split()
                recipe_to_terms[recipe_number].update(ingredients_to_terms)
            #如果此recipe有directions,统计步骤数量存入数据库,将此directions句子分割为一组单词并存入数据库 
            if 'directions' in recipe.keys()
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值