Python数据转换

时间:2018-07-26 10:23:59

标签: python python-3.x

我正在寻找一种Python解决方案来转换输入文件并将其原样读取为用PYTHON3编写的程序。

我的输入文件包含以下数据:

    { "h" : ["a","c","e"],
      "d" : ["d", "a","g"],
      "e" : ["f", "a", "b", "c"],
      "b" : ["d","c"],
      "c" : ["g", "c","a"],
      "g" : ["w","x","y"]
    }

我尝试了以下

a)datafile = open("infile.txt","r").read()
   错误消息:TypeError:字符串索引必须为整数

b)datafile = open("infile.txt","r").readline()
   错误消息:TypeError:字符串索引必须为整数

c)datafile = open("infile.txt","r").readlines()
   错误消息:TypeError:列表索引必须是整数或切片,而不是str

顺便说一下,我是Python的新手。

2 个答案:

答案 0 :(得分:0)

一种解决方案是:

import ast
datafile = open("infile.txt","r").read()
values = ast.literal_eval(''.join(datafile.splitlines()))
values['h']

根据Evgeny的建议,您也可以使用json模块:

import json
json_data=open('myfile.txt').read()

data = json.loads(json_data)
print(data['h'])

答案 1 :(得分:0)

您现在应该已经意识到python中字典的功能,下面的代码将为您提供帮助。假设您的文件名为file1.txt。现在,正如注释中提到的那样,您应该使用json库

with open("file1.txt") as fp:
    read=json.load(fp)

现在打印读取将为您提供数据字典

print(read)

将打印您的字典

  

{'g':['w','x','y'],'c':['g','c','a'],'e':['f',' a','b','c'],'d':['d','a','g'],'h':['a','c','e'],'b ':['d','c']}

注意:-不要忘记导入json。

  

导入json

重要。这是一个非常简单的问题。请不要提出这样的问题并为他们获得赞成票