[英]Converting txt file into a list of dictionaries
I am trying to convert a file with string dictionaries into a list of dictionaries.我正在尝试将带有字符串字典的文件转换为字典列表。 The file can be found here: https://github.com/szczor/sharing/blob/master/data.txt .
该文件可以在这里找到: https://github.com/szczor/sharing/blob/master/data.txt 。 Here is how I try it:
这是我的尝试方法:
lista = []
with open(os.path.join(path_to_data, 'data.txt')) as filehandle:
for line in filehandle:
# remove linebreak which is the last character of the string
currentPlace = line[:-1]
# add item to the list
lista.append(currentPlace)
So I have a list, now with elements which are string.所以我有一个列表,现在包含字符串元素。
print(type(lista[0]))
Now trying to convert those strings to dictionaries with现在尝试将这些字符串转换为字典
lista = [json.loads(str(string.replace('\'','\"'))) for string in lista]
But get an error但是得到一个错误
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I tried the same method with manually created list and everything worked, but have no idea why it does not work with my txt file.我用手动创建的列表尝试了相同的方法,一切正常,但不知道为什么它不适用于我的 txt 文件。
You can use ast.literal_eval
for this:您可以为此使用
ast.literal_eval
:
import ast
with open(os.path.join(path_to_data, 'data.txt')) as fp:
lines = fp.readlines()
# if there are irregularities, use a try/except to pass these (note, you may wish to use a logger in practice)
output = []
for line in lines:
try:
output.append(ast.literal_eval(line))
except ValueError:
print("malformed string; skipping this line")
except SyntaxError:
print("looks like some encoding errors with this file...")
output: output:
[{'Lines': '130',
'Lon': 21.0082356,
'VehicleNumber': '1000',
'Time': '2020-12-23 14:19:31',
'Lat': 52.207217,
'Brigade': '2'},
{'Lines': '213',
'Lon': 21.1013111,
'VehicleNumber': '1001',
'Time': '2020-12-23 15:40:37',
'Lat': 52.2230756,
'Brigade': '2'},
{'Lines': '130',
'Lon': 21.003573,
'VehicleNumber': '1002',
'Time': '2020-12-23 15:40:39',
'Lat': 52.2060591,
'Brigade': '1'},
{'Lines': '311',
'Lon': 21.0807406,
'VehicleNumber': '1003',
'Time': '2020-12-23 15:40:35',
'Lat': 52.2414656,
'Brigade': '2'},
{'Lines': '213',
'Lon': 21.1746171,
'VehicleNumber': '1004',
'Time': '2020-12-23 15:40:24',
'Lat': 52.186474,
'Brigade': '3'},...
i could not comment to your question due to some privileges, try由于某些特权,我无法对您的问题发表评论,请尝试
for line in filehandle.readlines(): #instead of just filehandle
This oughta do the trick.这应该可以解决问题。
ast.literal_eval()
should be able to parse dict strings like those in the data file: ast.literal_eval()
应该能够解析数据文件中的字典字符串:
import ast
with open(os.path.join(path_to_data, 'data.txt')) as filehandle:
lista = [
ast.literal_eval(line.strip())
for line
in filehandle
]
This is how i would approach:这就是我的处理方式:
f = open("data.txt", "r")
my_list = []
for x in f: #read the sheet line by line
dict_x = eval(x) #convert each line to dict
my_list.append(dict_x)
f.close()
Alternatively, eval() can also be substituted by dict()或者, eval() 也可以用 dict() 代替
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.