首页 > 解决方案 > 读取文本文件并在 python 中解析

问题描述

我有一个文本文件(.txt),如下所示:


日期、日期、宗派、1、2、3

1、太阳、1-1、123、345、678

2、周一、2-2、234、585、282

3、周二、2-2、231、232、686


有了这些数据,我想做以下事情:

1)逐行读取文本文件作为列表中的单独元素

对于这两个,我做了这些。

file = open('abc.txt', mode = 'r', encoding = 'utf-8-sig')
lines = file.readlines()
file.close()
my_dict = {}
my_list = []
for line in lines:
    line = line.split(',')
    line = [i.strip() for i in line]

2) 将第一行(Date, Day, Sect, 1, 2, 3) 设置为键,将其他行设置为字典中的值。

    my_dict['Date'] = line[0]
    my_dict['Day'] = line[1]
    my_dict['Sect'] = line[2]
    my_dict['1'] = line[3]
    my_dict['2'] = line[4]
    my_dict['3'] = line[5]

上面的代码有两个问题: 1)将第一行也设置为字典。2)如果我将其添加到列表中,如下所示,它只会将最后一行保留为列表中的所有元素。

3) 创建一个包含字典作为元素的列表。

    my_list.append(my_dict)    

4)子集我想要的元素。

我无法从这里编写任何代码。但我要做的是满足条件的子集元素:例如,选择字典中 Sect 为 2-2 的元素。那么想要的结果可能如下:

>> [{'Date': '2', 'Day': 'Mon', 'Sect': '2-2', '1': '234', '2': '585', '3': '282'}, {'Date': '3', 'Day': 'Tue', 'Sect': '2-2', '1': '231', '2':'232', '3':'686'}]

谢谢,

标签: pythonpython-3.xlistparsing

解决方案


@supremed14,您也可以在阅读文件后尝试以下代码来准备字典列表。

数据.txt

由于文本文件中有空格。在字符串上定义的strip()方法将解决这个问题。

Date, Day, Sect, 1, 2, 3

1, Sun, 1-1, 123, 345, 678

2, Mon, 2-2, 234, 585, 282

3, Tue, 2-2, 231, 232, 686

源代码:

在这里,您无需担心关闭文件。它将由 Python 处理。

import json
my_list = [];

with open('data.txt') as f:
    lines = f.readlines() # list containing lines of file
    columns = [] # To store column names

    i = 1
    for line in lines:
        line = line.strip() # remove leading/trailing white spaces
        if line:
            if i == 1:
                columns = [item.strip() for item in line.split(',')]
                i = i + 1
            else:
                d = {} # dictionary to store file data (each line)
                data = [item.strip() for item in line.split(',')]
                for index, elem in enumerate(data):
                    d[columns[index]] = data[index]

                my_list.append(d) # append dictionary to list

# pretty printing list of dictionaries
print(json.dumps(my_list, indent=4))

输出:

[
    {
        "Date": "1",
        "Day": "Sun",
        "Sect": "1-1",
        "1": "123",
        "2": "345",
        "3": "678"
    },
    {
        "Date": "2",
        "Day": "Mon",
        "Sect": "2-2",
        "1": "234",
        "2": "585",
        "3": "282"
    },
    {
        "Date": "3",
        "Day": "Tue",
        "Sect": "2-2",
        "1": "231",
        "2": "232",
        "3": "686"
    }
]

推荐阅读