#python #json #dictionary
#питон #json #словарь #python
Вопрос:
Я создаю поисковую систему для поиска рецептов. У меня есть JSON-файл, который был загружен в словарь рецептов. Я пытаюсь подсчитать, сколько раз появлялась конкретная работа в токене, и если да, добавьте единицу к значению счетчика. В этом случае title_c etc добавляет единицу, когда строка встречается в значении словаря, которое соответствует ключу ‘title’.
import json
import numpy as np
import string
file = open('recipes.json')
recipes = json.load(file)
def tokenisation(input_string):
#functions to remove digits and punctuation and replace it with whitespace
d_translate = str.maketrans(string.digits, ' '*len(string.digits))
p_translate = str.maketrans(string.punctuation, ' '*len(string.punctuation))
#clean the string
new_string = input_string.translate(d_translate)
new_string = new_string.translate(p_translate)
new_string = new_string.lower()
#split the string
splitted_string = new_string.split(" ")
#make a list to store tokens in
tokens = []
#checking length of token
for token in splitted_string:
if len(token) > 3:
tokens.append(token)
return tokens
def search(query, ordering = 'normal', count = 10):
token_list = tokenisation(query)
for recipe in recipes:
title_c = 0
cat_c = 0
ing_c = 0
dire_c = 0
for token in token_list:
for key, value in recipe.items():
if (token in recipe.values()) and (key == 'title'):
title_c = 1
elif (token in recipe.values()) and (key == 'categories'):
cat_c = 1
elif (token in recipe.values()) and (key == 'ingredients'):
ing_c = 1
elif (token in recipe.values()) and (key == 'directions'):
dire_c = 1
search('cheese!cheddar', 'normal', 10)
В конце значения в цикле for ближе к концу должны быть ненулевыми, но при печати они равны нулю. Я убедился, что в поисковом запросе есть токены, которые указаны в первом «рецепте» ниже:
{
"title": ""Adult" Pimiento Cheese ",
"categories": [
"Cheese",
"Vegetable",
"No-Cook",
"Vegetarian",
"Quick amp; Easy",
"Cheddar",
"Hot Pepper",
"Winter",
"Gourmet",
"Alabama"
],
"ingredients": [
"2 or 3 large garlic cloves",
"a 2-ounce jar diced pimientos",
"3 cups coarsely grated sharp Cheddar (preferably English, Canadian, or Vermont; about 12 ounces)",
"1/3 to 1/2 cup mayonnaise",
"crackers",
"toasted baguette slices",
"cruditu00e9s"
],
"directions": [
"Force garlic through a garlic press into a large bowl and stir in pimientos with liquid in jar. Add Cheddar and toss mixture to combine well. Stir in mayonnaise to taste and season with freshly ground black pepper. Cheese spread may be made 1 day ahead and chilled, covered. Bring spread to room temperature before serving.",
"Serve spread with accompaniments."
],
"rating": 3.125
}
Ответ №1:
Первым элементом в JSON является «title», который представляет собой строку. При вызове recipe.items()
он прерывается, поскольку строки не имеют items()
вызова. Добавление проверки типа строки перед тем, как она позволит успешно выполнить код.
import json
import numpy as np
import string
file = open('recipes.json')
recipes = json.load(file)
def tokenisation(input_string):
#functions to remove digits and punctuation and replace it with whitespace
d_translate = str.maketrans(string.digits, ' '*len(string.digits))
p_translate = str.maketrans(string.punctuation, ' '*len(string.punctuation))
#clean the string
new_string = input_string.translate(d_translate)
new_string = new_string.translate(p_translate)
new_string = new_string.lower()
#split the string
splitted_string = new_string.split(" ")
#make a list to store tokens in
tokens = []
#checking length of token
for token in splitted_string:
if len(token) > 3:
tokens.append(token)
return tokens
def search(query, ordering = 'normal', count = 10):
token_list = tokenisation(query)
for recipe in recipes:
print(recipe)
title_c = 0
cat_c = 0
ing_c = 0
dire_c = 0
for token in token_list:
if not isinstance(recipe, str): # Make sure we aren't checking the string for items()
for key, value in recipe.items():
if (token in recipe.values()) and (key == 'title'):
title_c = 1
elif (token in recipe.values()) and (key == 'categories'):
cat_c = 1
elif (token in recipe.values()) and (key == 'ingredients'):
ing_c = 1
elif (token in recipe.values()) and (key == 'directions'):
dire_c = 1
search('cheese!cheddar', 'normal', 10)
Комментарии:
1. Это было то, о чем я думал с точки зрения наличия строки. Я обнаружил, что вместо использования recipe.values() я мог бы использовать str(значение). lower() . Это хорошая замена?
2. Да, это будет точнее того, что вы пытаетесь проверить