读取文本文件并在python中解析

新手上路,请多包涵

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


日期、日、节、1、2、3

1, 太阳, 1-1, 123, 345, 678

2, 星期一, 2-2, 234, 585, 282

3, 星期二, 2-2, 231, 232, 686


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

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

  • 用逗号分割元素

  • 删除列表中不需要的元素(’\n’)

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

 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]

  1. 将第一行(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)如果我将它添加到列表中,如下所示,它只保留最后一行作为列表中的所有元素。

  1. 创建一个包含字典作为元素的列表。
     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'}]

谢谢,

原文由 supremed14 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 543
1 个回答

@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"
    }
]

原文由 hygull 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题