sup*_*d14 4 python parsing list python-3.x
我有一个文本文件(.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]
Run Code Online (Sandbox Code Playgroud)
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]
Run Code Online (Sandbox Code Playgroud)
上面的代码有两个问题:1)也将第一行设置为字典。2)如果我将其添加到列表中,如下所示,它只会将最后一行保留为列表中的所有元素。
3) 创建一个包含字典作为元素的列表。
my_list.append(my_dict)
Run Code Online (Sandbox Code Playgroud)
4)对我想要的元素进行子集化。
我无法从这里编写任何代码。但我想做的是满足条件的子集元素:例如,选择字典中宗派为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'}]
Run Code Online (Sandbox Code Playgroud)
谢谢,
@supremed14,您还可以尝试以下代码在读取文件后准备字典列表。
由于文本文件中存在空格。在字符串上定义的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
Run Code Online (Sandbox Code Playgroud)
在这里你不需要担心关闭文件。它将由 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))
Run Code Online (Sandbox Code Playgroud)
[
{
"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"
}
]
Run Code Online (Sandbox Code Playgroud)