简体   繁体   English

如何阅读文本文件以转换成字典?

[英]How to read text file to convert to dictionary?

I'm trying to read a text file contains dictionaries separated by comma, and convert to a list of dictionaries. 我正在尝试读取一个文本文件,其中包含用逗号分隔的词典,并将其转换为词典列表。

How can I do this with python? 如何使用python做到这一点?

I tried to read as json file or use split method 我试图读取为json文件或使用拆分方法

{
    "id": "b1",
    "name": "Some Name" 
},
{
    "id": "b2",
    "name": "Another Name"
},
....

result should be: 结果应该是:

[ {"id" : "b1", "name" : "Some Name"} , {"id" : "b2", "name" : "Another Name"}, .... ] [{“ id”:“ b1”,“ name”:“某些名称”},{“ id”:“ b2”,“ name”:“另一个名称”},....]

If your file is not too big, you can do the following: 如果文件不太大,则可以执行以下操作:

import json

with open('filename.txt', 'r') as file:
    result = json.loads('[' + file.read() + ']')

You can use json module in python 您可以在python中使用json模块

JSON (JavaScript Object Notation), specified by RFC 7159 (which obsoletes RFC 4627) and by ECMA-404, is a lightweight data interchange format inspired by JavaScript object literal syntax (although it is not a strict subset of JavaScript). RFC 7159(已淘汰RFC 4627)和ECMA-404指定的JSON(JavaScript对象表示法)是一种受JavaScript对象文字语法启发的轻量级数据交换格式(尽管它不是JavaScript的严格子集)。

json exposes an API familiar to users of the standard library marshal and pickle modules. json公开了标准库编组和pickle模块用户熟悉的API。 https://docs.python.org/2/library/json.html https://docs.python.org/2/library/json.html

In your case if your file is a valid json file then you can use json.loads() method directly 如果您的文件是有效的json文件,则可以直接使用json.loads()方法

import json

with open('test.txt', 'r') as file:
    result = json.loads(file.read())

Welcome to Stack Overflow..! 欢迎来到堆栈溢出..!

If you are using a JSON file to store data, then I highly recommend the Python JSON Library . 如果您使用JSON文件存储数据,那么我强烈建议您使用Python JSON Library How to use it you ask..? 您问如何使用它? Read this 这个

If you plan on using a Text file to store data, I recommend that you store the data a bit differently than the JSON format 如果计划使用文本文件存储数据,建议您将数据存储与JSON格式有所不同

b1,Some Name
b2,Another Name
.
.

This would make reading the text file way easier . 这将使阅读文本文件的方式更加容易 Just use the split() command to separate the lines from one another and then use split(",") on each of the lines to separate the ID from the Name. 只需使用split()命令将行彼此分开,然后在每一行上使用split(",")即可将ID与名称分开。

Here is the code: 这是代码:

list = open("filename.txt").read().split("\n")
dictionaryList = []
for item in list:
    id, name = item.split(",")
    dictionaryList.append({id:name})

Hope this works..! 希望这可以..! SDA SDA

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM