Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.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 - Fatal编程技术网

如何将以下文件上载到Python中,以从文件中获取特定结构?跟随正文看一个例子

如何将以下文件上载到Python中,以从文件中获取特定结构?跟随正文看一个例子,python,Python,文件: 我需要上传到Python中,并以以下形式获取: 0 3 3.0277 0 14 4.8251 1 6 2.8984 2 3 4.5238 2 12 1.9643 3 2 4.5238 非常感谢,谢谢你可以使用re来解析文本: graph_latency = {'0':{'3':3.0277,'14':4.8251} ,'1':{'6':2.8984} ,'2':{'3':4.5238,'12':1.9362037455854288} ,'3':{'0':4.5

文件:

我需要上传到Python中,并以以下形式获取:

 0 3 3.0277

 0 14 4.8251

 1 6 2.8984

 2 3 4.5238

 2 12 1.9643

3 2 4.5238
非常感谢,谢谢你可以使用re来解析文本:

graph_latency = {'0':{'3':3.0277,'14':4.8251}

,'1':{'6':2.8984}

,'2':{'3':4.5238,'12':1.9362037455854288}

,'3':{'0':4.5238,'2':4.5238}}
产出:

import re
from collections import defaultdict
from pprint import pprint

data_from_file = """
 0 3 3.0277

 0 14 4.8251

 1 6 2.8984

 2 3 4.5238

 2 12 1.9643

3 2 4.5238"""

def transform_to_my_format(data):
    d = defaultdict(dict)
    for (i1, i2, i3) in re.findall(r'([\d\.]+)\s+([\d\.]+)\s+([\d\.]+)', data):
        d[i1].update({i2: float(i3)})
    return d

pprint(transform_to_my_format(data_from_file))

下一个外部结构是什么?到目前为止你试过什么?您得到了什么错误/输出?可能是重复的感谢Adrej,这是一种新的语言,对我来说,它的工作非常好,如何从一个文件中获得它?因为文件将是python中a代码的条目。谢谢again@Richard您可以尝试使用data\u from\u file=open'path/to/my/file.txt',r.readHey@Andrej,我需要像数字一样获取十进制数字,而不是字符串,我的意思是没有。不是像这样的“4.8251”-以这种方式4.8251。由于我需要做一些操作…谢谢,我试过了,但是我把int放进去了,根据你的回答,我注意到它是浮动的。我能给你发邮件吗?我被一个密码卡住了,我需要一只手。谢谢
defaultdict(<class 'dict'>,
            {'0': {'14': 4.8251, '3': 3.0277},
             '1': {'6': 2.8984},
             '2': {'12': 1.9643, '3': 4.5238},
             '3': {'2': 4.5238}})