繁体   English   中英

如何将从.txt文件中读取的这些元素保存到python中的数组/矩阵中

[英]How to save these elements read from a .txt file into an array/matrix in python

我有一个 .txt 文件,其中包含如下所示的元素:

Smith 25 35 NC
Johnson 12 4 OH
Jones 23 14 FL
Lopez 2 7 TX

我想逐行读取 .txt 文件,并将每个元素(名称、数字、数字、状态)保存在数组矩阵或列表 4 x number_of_people 中,同时忽略任何空格。 我试图不使用split() ,但可以使用split() () 的“手动”形式,如下所示split1

def split1(line,delim):
    s=[]
    j=0
    for i in range (len(line)):
        if delim== line [i]:
            s.append(line[j:i])
            j=i+1
    s.append (line[j:])
    return s



f = open("Names.txt")
number_of_people = 0


#This portion is meant to go through the entire .txt file, 1 time and count how many people are listed on the file so I can make an appropiatly sized matrix, in the case of the example is 4
while True:
        file_eof = f.readline()
        if file_eof != '':
            number_of_people = number_of_people + 1
        if file_eof == '':
                break

#This portion reads through the .txt file agin and saves the names of the list
while True:
        file_eof = f.readline()
        if file_eof != '':
            split1(file_eof, '')
            #print(file_eof)
        if file_eof == '':
                print('No more names on the list')
                break


f.close()

我知道这里可能缺少一些东西,而这正是我需要帮助的地方。 如果有任何比我得到的“更好”的方法来处理这个问题,请让我知道并在可能的情况下告诉我。

感谢您的时间!

我不明白你为什么要先创建一个特定大小的数组。 我想你有 C 的背景? 文件有多大?

以下是读取和存储该信息的 2 种 Pythonic 方法:

filename = r"data.txt"

# Access items by index, e.g. people_as_list[0][0] is "Smith"
with open(filename) as f: # with statement = context manager = implicit/automatic closing of the file
    people_as_list = [line.split() for line in f] # List comprehension

# Access items by index, then key, e.g. people_as_dict[0]["name"] is "Smith"
people_as_dict = []
with open(filename) as f:
    for line in f:
        name, number1, number2, state = line.split() # Iterable unpacking
        person = {}
        person["name"] = name
        person["number1"] = number1
        person["number2"] = number2
        person["state"] = state
        people_as_dict.append(person)

print(people_as_list)
print(people_as_dict)

输出:

[['Smith', '25', '35', 'NC'], ['Johnson', '12', '4', 'OH'], ['Jones', '23', '14', 'FL'], ['Lopez', '2', '7', 'TX']]
[{'name': 'Smith', 'number1': '25', 'number2': '35', 'state': 'NC'}, {'name': 'Johnson', 'number1': '12', 'number2': '4', 'state': 'OH'}, {'name': 'Jones', 'number1': '23', 'number2': '14', 'state': 'FL'}, {'name': 'Lopez', 'number1': '2', 'number2': '7', 'state': 'TX'}]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM