我有一个文本文件(.txt),如下所示:
日期、日期、节、1、2、3
1,Sun,1-1,123,345,678
2,星期一,2-2,234,585,282
3,Tue,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)将第一行(日期、日期、节、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)子集我想要的元素。
我不能在这里写任何代码。但是我想要做的是满足条件的子集元素:例如,在字典中选择这个元素,其中组为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'}]
谢谢,
发布于 2018-07-15 04:17:35
@14,您也可以尝试下面的代码来在读取文件之后准备字典列表。
data.txt
因为文本文件中有空格。定义在字符串上的样条()方法将解决这个问题。
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"
}
]
发布于 2018-07-15 03:54:13
使用熊猫是相当容易的:
输入:
$cat test.txt
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
业务:
import pandas as pd
df = pd.read_csv('test.txt', skipinitialspace=True)
df.loc[df['Sect'] == '2-2'].to_dict(orient='records')
输出:
[{'1': 234, '2': 585, '3': 282, 'Date': 2, 'Day': 'Mon', 'Sect': '2-2'},
{'1': 231, '2': 232, '3': 686, 'Date': 3, 'Day': 'Tue', 'Sect': '2-2'}]
发布于 2018-07-15 04:12:32
如果您的.txt文件是CSV格式的:
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
您可以使用csv
库:
from csv import reader
from pprint import pprint
result = []
with open('file.txt') as in_file:
# create a csv reader object
csv_reader = reader(in_file)
# extract headers
headers = [x.strip() for x in next(csv_reader)]
# go over each line
for line in csv_reader:
# if line is not empty
if line:
# create dict for line
d = dict(zip(headers, map(str.strip, line)))
# append dict if it matches your condition
if d['Sect'] == '2-2':
result.append(d)
pprint(result)
它给出了以下列表:
[{'1': '234', '2': '585', '3': '282', 'Date': '2', 'Day': 'Mon', 'Sect': '2-2'},
{'1': '231', '2': '232', '3': '686', 'Date': '3', 'Day': 'Tue', 'Sect': '2-2'}]
https://stackoverflow.com/questions/51345024
复制相似问题