创建一个打开文件并提取数据以制作字典的函数

Creating a function that opens a file and extracts data to make a dictionary

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

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

唯一的错误是您试图附加到 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

由于 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