简体   繁体   English

从 txt 中读取多行并在 Python 中存储到多个列表

[英]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
  • First step: split by colon parts = line.split(':')第一步:用冒号分割parts = line.split(':')
  • Second: split the second part by comma to get the list food_list = parts[1].split(',')第二:用逗号分割第二部分得到列表food_list = parts[1].split(',')
  • Last step: putting it all together in a 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.

相关问题 在Python中读取文件输入到多个列表的行 - Reading lines of file input into multiple lists in Python 在Python中,如何从空格分隔的.txt文件中获取整数列表,并在多行上使用'\\ r \\ n'分隔数字? - In Python, how to get integer lists from a .txt file with space separated and '\r\n' delimited numbers on multiple lines? 如何通过读取.txt文件为每个键创建包含多个“列表”的Python字典? - How to create Python dictionary with multiple 'lists' for each key by reading from .txt file? 从 python 中读取具有多个列表列表的文件 - Reading a file with multiple list of lists from into python 从外部文件读取多行-Python - Reading multiple lines from an external file - Python 从.txt填充熊猫数据框,从多条.txt行读取单个数据框行信息 - Populate pandas dataframe from .txt reading single dataframe row information from multiple .txt lines 将 TXT 文件中的多个列表插入到字典中?,python - insert multiple lists from a TXT file into to dictionary?, python Python-将多行读入列表 - Python - Reading multiple lines into list 如何在 python 中将多行变成多个列表? - how to turn multiple lines into multiple lists in python? Python 3.3-从列表和.txt中读取多项选择,然后评分 - Python 3.3 - Multiple choice reading from list and .txt then grade
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM