Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/366.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 尝试将文本文件转换为数据结构_Python_Python 3.x_Numpy_Multidimensional Array - Fatal编程技术网

Python 尝试将文本文件转换为数据结构

Python 尝试将文本文件转换为数据结构,python,python-3.x,numpy,multidimensional-array,Python,Python 3.x,Numpy,Multidimensional Array,我喜欢这个文本数据如下内容。我正在尝试的是将此文本转换为数据结构字典列表或能够处理的列表列表 test.txt 输出格式如下所示: 0 1 1 --------------- 3| 1 1 1 5| 0 1 0 6| 1 0 0 我尝试了很多事情,但不幸的是没有成功 我不知道这是否正是您想要的结构,但请尝试以下方法: import collections txt = """0 1

我喜欢这个文本数据如下内容。我正在尝试的是将此文本转换为数据结构字典列表或能够处理的列表列表

test.txt

输出格式如下所示:

   0     1      1
   ---------------
3| 1    1       1
5| 0    1      0
6| 1    0       0

我尝试了很多事情,但不幸的是没有成功

我不知道这是否正是您想要的结构,但请尝试以下方法:

import collections

txt = """0           1           1
3,1         3,1         3,1
5,0         5,1         5,0
6,1         6,0         6,0"""

header = list(map(int,txt.splitlines()[0].split()))

output = collections.OrderedDict()
for line in txt.splitlines()[1:]:
    cols = line.split()
    row_num = int(cols[0].split(",")[0])

    vals = [(header[i],int(c.split(",")[1])) for i, c in enumerate(cols)]
    output[row_num] = vals

print(output)
输出:

OrderedDict([('3', [(0, 1), (1, 1), (1, 1)]), ('5', [(0, 0), (1, 1), (1, 0)]), ('6', [(0, 1), (1, 0), (1, 0)])])
要加载文件,请执行以下操作:

with open("file.txt") as f:
    txt = f.read()

你想要什么结构?名单?字典列表?列表词典?字典中的字典?还有,到目前为止你试过什么?你当前的代码有什么问题?我是初学者,所以我花了很多时间试图理解如何做,但没有成功。你能发布你的代码,如果出现错误消息吗?另外,对于有两个名为1的列这一事实,您想做些什么?问题到底是什么?堆栈溢出不是免费的代码编写服务。请参阅:,。谢谢,但在我的情况下,它是关于一个txt文件而不是txt字符串,是的,这正是我所需要的。请更新您的答案,使其适合于file.txt?打开'result.info'作为infle:header=listmaint,infle.read.splitlines[0]。拆分输出=collections.OrderedDict用于inflee.read.splitlines[1:]:printline cols=line.split row_num=cols[0][0]vals=[header[i],intc.split[1]for i,c in enumeratecols]output[row_num]=vals printOutput我在哪里出错?我收到了空订单
with open("file.txt") as f:
    txt = f.read()