提问人:This_guy 提问时间:11/22/2022 最后编辑:buranThis_guy 更新时间:11/22/2022 访问量:50
将常用的 file.txt 格式转换为 Dictionaty 格式,嵌套字典 Python
convert the usual file.txt format into dictionaty format, nested dictionary python
问:
我正在打开一本烹饪书“recipes.txt”,它的内容是这样的:
f = open('recipes.txt', 'r', encoding='utf-8')
for x in f:
print(x)
结果:
Omelet
3
Egg | 2 | PCS
Milk | 100 | ml
Tomato | 2 | PCS
Peking Duck
4
Duck | 1 | PCS
Water | 2 | l
Honey | 3 | t.sp
Soy sauce | 60 | ml
我需要读取/将其转换为嵌套字典格式,如下所示:
cook_book = {
'Omelet': [
{'ingredient_name': 'Egg', 'quantity': 2, 'measure': 'PCS'},
{'ingredient_name': 'Milk', 'quantity': 100, 'measure': 'ml'},
{'ingredient_name': 'Tomato', 'quantity': 2, 'measure': 'PCS'}
],
'Peking Duck': [
{'ingredient_name': 'Duck', 'quantity': 1, 'measure': 'PCS'},
{'ingredient_name': 'Water', 'quantity': 2, 'measure': 'l'},
{'ingredient_name': 'Honey', 'quantity': 3, 'measure': 't.sp'},
{'ingredient_name': 'Soy sauce', 'quantity': 60, 'measure': 'ml'}
]
}
我无法自己获得完全想要的格式。任何建议将不胜感激。
答:
1赞
Hunter
11/22/2022
#1
你所做的只是从文件中读取,而你应该从中获取值并在字典中分配它。
cook_book = {}
indexes = []
with open('recipes.txt', 'r', encoding='utf-8') as fp:
data = fp.read()
linedData = data.split('\n')
i = 0
for line in data.split('\n'):
try:
amount = int(line)
indexes.append(i)
indexes.append(amount)
except:
pass
i += 1
for x in range(len(indexes)):
if (x % 2) == 0:
mealName = linedData[indexes[x]-1]
focusedData = linedData[indexes[x] + 1:]
focusedData = focusedData[:(indexes[x+1])]
totalIngredients = []
for line in focusedData:
ingredients = {}
try:
name, amm, ref = line.split(' | ')
ingredients['ingredient_name'] = name
ingredients['quantity'] = int(amm)
ingredients['measure'] = ref
except:
pass
totalIngredients.append(ingredients)
cook_book[mealName] = totalIngredients
print(cook_book)
创建以下输出:
{'Omelette': [{'ingredient_name': 'Egg', 'quantity': 2, 'measure': 'PCS'}, {'ingredient_name': 'Milk', 'quantity': 100, 'measure': 'ml'}, {'ingredient_name': 'Tomato', 'quantity': 2, 'measure': 'PCS'}], 'Peking duck': [{'ingredient_name': 'Duck', 'quantity': 1, 'measure': 'PCS'}, {'ingredient_name': 'Water', 'quantity': 2, 'measure': 'l'}, {'ingredient_name': 'Honey', 'quantity': 3, 'measure': 'tbsp'}, {'ingredient_name': 'Soy sauce', 'quantity': 60, 'measure': 'ml'}], 'Baked potatoes': [{'ingredient_name': 'Potatoes', 'quantity': 1, 'measure': 'kg'}, {'ingredient_name': 'Garlic', 'quantity': 3, 'measure': 'tooth'}, {'ingredient_name': 'Gouda cheese', 'quantity': 100, 'measure': 'G'}], 'Fajitos': [{'ingredient_name': 'Beef', 'quantity': 500, 'measure': 'G'}, {'ingredient_name': 'Sweet pepper', 'quantity': 1, 'measure': 'PCS'}, {'ingredient_name': 'Lavash', 'quantity': 2, 'measure': 'state'}, {'ingredient_name': 'Wine vinegar', 'quantity': 1, 'measure': 'tbsp'}, {'ingredient_name': 'Tomato', 'quantity': 2, 'measure': 'state'}]}
但是,当格式化时,它会创建所需的输出:
{
'Omelette': [
{'ingredient_name': 'Egg', 'quantity': 2, 'measure': 'PCS'},
{'ingredient_name': 'Milk', 'quantity': 100, 'measure': 'ml'},
{'ingredient_name': 'Tomato', 'quantity': 2, 'measure': 'PCS'}
],
'Peking duck': [
{'ingredient_name': 'Duck', 'quantity': 1, 'measure': 'PCS'},
{'ingredient_name': 'Water', 'quantity': 2, 'measure': 'l'},
{'ingredient_name': 'Honey', 'quantity': 3, 'measure': 'tbsp'},
{'ingredient_name': 'Soy sauce', 'quantity': 60, 'measure': 'ml'}
],
'Baked potatoes': [
{'ingredient_name': 'Potatoes', 'quantity': 1, 'measure': 'kg'},
{'ingredient_name': 'Garlic', 'quantity': 3, 'measure': 'tooth'},
{'ingredient_name': 'Gouda cheese', 'quantity': 100, 'measure': 'G'}
],
'Fajitos': [
{'ingredient_name': 'Beef', 'quantity': 500, 'measure': 'G'},
{'ingredient_name': 'Sweet pepper', 'quantity': 1, 'measure': 'PCS'},
{'ingredient_name': 'Lavash', 'quantity': 2, 'measure': 'state'},
{'ingredient_name': 'Wine vinegar', 'quantity': 1, 'measure': 'tbsp'},
{'ingredient_name': 'Tomato', 'quantity': 2, 'measure': 'state'}
]
}
请记住,可能有更有效的方法来实现所需的输出,并且会有办法重构我的代码,但这是我对这个问题的尝试。
希望这会有所帮助。
2赞
Chris
11/22/2022
#2
嘿,也许比@Hunters解决方案短一点
with open('recipes.txt', 'r', encoding='utf-8') as recipes:
cook_book = {}
for line in recipes:
if (line.replace("\n", "")).isnumeric() or line == "\n": # Ignore unwanted lines
continue
elif "|" not in line: # Initialize individual recipes
current_recipe = line.replace("\n", "")
cook_book[current_recipe] = []
elif len(line.strip("|")) > 2: # Add ingredients
ingredient = {}
ingredient_lst = line.split("|")
ingredient["ingredient_name"] = ingredient_lst[0].strip()
ingredient["quantity"] = ingredient_lst[1].strip()
ingredient["measure"] = ingredient_lst[2].replace("\n", "").strip()
cook_book[current_recipe].append(ingredient)
print(cook_book)
如果您加载任何文件并从中读取,您应该始终使用 with 块 - Python 将自行处理关闭文件等。
编辑:
如果要将cook_book转储到 json 文件,可以添加以下内容
import json
with open('cook_book.json', 'w', encoding='utf-8') as f:
json.dump(cook_book, f, ensure_ascii=False, indent=4)
结果如下:
{
"Omelet": [
{
"ingredient_name": "Egg ",
"quantity": " 2 ",
"measure": " PCS"
},
{
"ingredient_name": "Milk ",
"quantity": " 100 ",
"measure": " ml"
},
{
"ingredient_name": "Tomato ",
"quantity": " 2 ",
"measure": " PCS"
}
],
"Peking Duck": [
{
"ingredient_name": "Duck ",
"quantity": " 1 ",
"measure": " PCS"
},
{
"ingredient_name": "Water ",
"quantity": " 2 ",
"measure": " l"
},
{
"ingredient_name": "Honey ",
"quantity": " 3 ",
"measure": " t.sp"
},
{
"ingredient_name": "Soy sauce ",
"quantity": " 60 ",
"measure": " ml"
}
]
}
评论
0赞
Hunter
11/23/2022
这是我第一次尝试嵌套词典,所以这个答案可能值得一试
评论