我有一个txt文件,每行包含多个字符串,如下所示:
Hamburger: Ground Beef, Onion, Tomato, Bread, Ketchup
Pesto_Chicken: Chicken, Peppers, Pasta, Pesto
Surf_and_Turf: Steak, Fish
我想将其读入程序并为每行创建一个列表。理想情况下,使用每行的第一个单词(例如,Hamburger等)作为列表名称,但这并不重要。我只需要将每一行放入自己的列表中即可。到目前为止,我可以阅读并打印到控制台,但不确定如何将其存储为列表?
filepath = 'recipes.txt'
with open(filepath) as fp:
line = fp.readline()
cnt = 1
while line:
print("Line {}: {}".format(cnt, line.strip()))
line = fp.readline()
cnt += 1
答案 0 :(得分:1)
parts = line.split(':')
food_list = parts[1].split(',')
dict
foods = {} # declare a dict
with open('recipes.txt') as file:
for line in file:
parts = line.split(':')
food_type = parts[0]
food_list = parts[1].split(',')
foods[food_type] = food_list
答案 1 :(得分:0)
尝试完全满足您需要的split()方法。
获取第一个单词(作为标题):
parts = line.split(":")
title = parts[0]
然后将其他单词作为列表:
words_list = parts[1].split(", ")