创建打开文件并提取数据以生成字典的函数

2024-10-01 00:23:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含这些数据的文本文件,我需要创建一个函数,打开这个.txt文件,读取每一行,然后将其传输到python字典中。此字典将第一列作为键,然后相应的值将同时为“北距、东距”

Station Northings   Eastings
1   10001.00    10001.00
2   10070.09    10004.57
3   10105.80    10001.70

到目前为止,这是我唯一拥有的东西,当调用函数AttributeError: 'builtin_function_or_method' object has no attribute 'split'时,它有这个错误。对不起,我对这个很陌生

def parsefile(file_name):
    station = []
    norths = []
    easts = []
    dict_station = {}
    with open(file_name) as fn:
        for line in fn:
            (stat,north,east) = line.split()
            stat.append(stat)
            norths.append(north)
            easts.append(east)
            dict_station[stat] = (north,east)
            print(station, norths, easts)
        
        return dict_station

Tags: 数据name字典linedictstatfilefn
2条回答

由于Station、Northings和Eastings只有一个值,与其为它们创建单独的列表,不如尝试在此处使用以下代码,我不考虑将第一行存储为字典:

def parsefile(file_name):
    dict_station = {}
    with open(file_name) as fn:
        next(fn)
        for line in fn:
            temp = line.split()
            dict_station[temp[0]] = (temp[1],temp[2])
    return dict_station

唯一的错误是您试图附加到stat而不是station

但是你也在做一些不必要的事情。这样可以运行,而且效率更高

def parsefile(file_name):
    dict_station = {}
    with open(file_name) as fn:
        for line in fn:
            stat,north,east = line.split()
            dict_station[stat] = (north,east)
    return dict_station

相关问题 更多 >