简体   繁体   English

如何从txt文件中提取单独的第n行并将其分配给python 3中的key:value对?

[英]How to extract separate nth lines from a txt file and assign them to key:value pairs in python 3?

I'm learning how to code and I've run into a problem I don't have an answer to. 我正在学习如何编码,但遇到了无法解决的问题。 I have a text file from which I have to make three dictionaries: 我有一个文本文件,必须从中创建三个字典:

Georgie Porgie
87%
$$$
Canadian, Pub Food

Queen St. Cafe
82%
$
Malaysian, Thai

For the purpose of this thread I just want to ask how to extract the first line of each text block and store it as a key and the second line of each block as a value? 出于此线程的目的,我只想问一下如何提取每个文本块的第一行并将其存储为键,并将每个块的第二行存储为值? I am supposed to write a code using nothing more but the very basic functions and loops. 我应该只使用非常基本的功能和循环来编写代码。

Here is my code(once the file is opened): 这是我的代码(一旦打开文件):

d = {}
a = 0
for i in file:
    d[i] = i + 1
    a = i + 5
return(d)

Thank you. 谢谢。

First you have to read the file: 首先,您必须阅读文件:

with open("data.txt") as file:
    lines = file.readlines()

The with clause ensures it is closed after it is read. with子句可确保在读取后将其关闭。 Next, according to your description, a line contains a key if the index % 5 is 0. Then, the next line contains the value. 接下来,根据您的描述,如果index % 5为0,则一行包含一个键。然后,下一行包含该值。 With only "basic" elements of the language, you could construct your dictionary like this: 仅使用语言的“基本”元素,就可以像下面这样构造字典:

dic = {lines[idx].strip(): lines[idx + 1].strip() 
       for idx in range(0, len(lines), 5)}

This is a dictionary comprehension, which can also be written unfolded. 这是字典的理解,也可以展开显示。

Now you can also zip the keys and values first, so you can iterate them quite easily. 现在,您还可以首先压缩键和值,因此可以非常轻松地进行迭代。 This makes the dictionary comprehension more readable. 这使字典理解更具可读性。 The strip method is necessary though, since we want to get rid of the line breaks. 但是, 剥离方法是必需的,因为我们要摆脱换行符。

entries = zip(lines[::5], lines[1::5])
dic = {key.strip(): value.strip() for key, value in entries}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM