У меня есть следующий список словарей:
menu = [{"food": "basic lasagna", "description": "basic lasagna takes tomato sauce and ground beef ."}, {"food": "carbonara pasta", "description": "there are many types of pasta in this world, but carbonara pasta is one of the best ."}, {...}, ...]
Приходится выделять еду в описании тегами <food> food </food>, но я не знаю, как это сделать, не усложняя индексами. Моя первоначальная идея была:
for item in menu:
tag = item["food"]
if item["food"] in item["description"]:
i = tag.index()
tagging = "<food> " + tag + "</food>"
Но потом я застрял, потому что я действительно не знаю, как заменить элемент. Какие-либо предложения?





IIUC, то, что вам нужно, можно сделать с помощью метода replace:
import json
menu = [{"food": "basic lasagna", "description": "basic lasagna takes tomato sauce and ground beef ."}, {"food": "carbonara pasta", "description": "there are many types of pasta in this world, but carbonara pasta is one of the best ."}]
for item in menu:
item["description"] = item["description"].replace(item['food'], "<food>" + item['food'] + "</food>")
print(json.dumps(menu, indent=4))
Выход:
[
{
"food": "basic lasagna",
"description": "<food>basic lasagna</food> takes tomato sauce and ground beef ."
},
{
"food": "carbonara pasta",
"description": "there are many types of pasta in this world, but <food>carbonara pasta</food> is one of the best ."
}
]
да, именно об этом я и думал, спасибо!