[英]Reading multiple lines from txt and storing to multiple lists in Python
I have a txt file with multiple strings on each line as below:我有一个 txt 文件,每行有多个字符串,如下所示:
Hamburger: Ground Beef, Onion, Tomato, Bread, Ketchup
Pesto_Chicken: Chicken, Peppers, Pasta, Pesto
Surf_and_Turf: Steak, Fish
I'd like to read it into my program and create a list for each line.我想将它读入我的程序并为每一行创建一个列表。 Ideally using the first word of each line (ie Hamburger, etc.) as the list name, but that's not critical.
理想情况下,使用每行的第一个单词(即 Hamburger 等)作为列表名称,但这并不重要。 I just need to get each line into its own list.
我只需要将每一行都放入自己的列表中。 So far I can read it in and print to the console, but not sure how to store as a list??
到目前为止,我可以读取它并打印到控制台,但不确定如何存储为列表?
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
parts = line.split(':')
parts = line.split(':')
food_list = parts[1].split(',')
food_list = parts[1].split(',')
dict
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
give a try to the split() method which does exactly what you need.尝试 split() 方法,它完全符合您的需要。
Get the first word (as title):获取第一个单词(作为标题):
parts = line.split(":")
title = parts[0]
then the other words as a list:然后将其他单词作为列表:
words_list = parts[1].split(", ")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.