python - 读取文本文件并在 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]
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'}]
谢谢,
解决方案
@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"
}
]
推荐阅读
- android - 如何在 MVVM/retrofit Architecture 中使用 DataBinding 在 RecyclerView 的一行中设置数据?
- python - 静态方法包装器实际上在 python 中做了什么?
- java - ANTLR4 - 树模式匹配代码错误
- php - MYSQL 使用我的 PHP 将查询转换为 JSON
- java - RXJava 顺序执行 observable
- ios - Alamofire POST 参数没有通过
- python - 如何使用 Selenium 和 Python 上传文件
- python - 一个热编码一列有 28 个不同的国家,只有 6 个类
- javascript - 价值观严格相等的问题
- c# - 如何将一个项目反序列化为不同的类型?(牛顿软件、C#、.NET)