如何在 python 中将 txt 转换为字典

How to convert txt to dictionary in python

谁能解释一下为什么将这个 txt.file 转移到字典的代码是我在下面写的答案,因为我不明白流程。

任务:将此 txt 文件转换为字典

house_price.txt=

land, building, distance_to_center, price

70, 50, 15, 500

70, 60, 30, 400

70, 60, 55, 300

100, 50, 30, 700

100, 70, 25, 1000

100, 70, 50, 650

120, 100, 20, 2000

120, 80, 50, 1200

150, 100, 50, 1800

150, 90, 15, 3000

答案:

file_house_price = open("house_price.txt", "r")

data_house_price = file_house_price.readlines()

file_house_price.close()

key_house_price = data_house_price[0].replace("\n","").split(",")

house_price = []

for lines in data_house_price[1:]:
    
    lines_house_price = lines.replace("\n","").split(",")
    
    dict_house_price = dict()
    
    for i in range(len(lines_house_price)):
        
        dict_house_price[key_house_price[i]] = lines_house_price[i]
    
    house_price.append(dict_house_price)

print(house_price)

想问下这个key_house_price = data_house_price[0].replace("\n","").split(",")中的replace和split是什么意思 以及为什么索引为 0,以及这一行背后的含义 -> 对于 data_house_price[1:] 中的行和 这一行 -> dict_house_price[key_house_price[i]] = lines_house_price[i]

我已经在答案中添加了评论来解释流程,如果不够清楚,请在您的问题中添加更多细节:)

# Open file for reading
file_house_price = open("house_price.txt", "r")

# read all lines from the file into a variable
data_house_price = file_house_price.readlines()

# as we're done with the file, we can safely close it (we have all the data in memory)
file_house_price.close()

# the first line of the data is the column headers separated by comma
# so here we split that line on comma (removing the newline character as well, using replace)
# which gives us a list of strings (each column header)
key_house_price = data_house_price[0].replace("\n","").split(",")

house_price = []

# loop over all the remaining lines from the file (the [1:] gives us all lines, except the first as indexing starts at 0)
for lines in data_house_price[1:]:
    
    # get rid of newline character and split the line on comma
    lines_house_price = lines.replace("\n","").split(",")
    
    # create a dictionary for storing data for this line
    dict_house_price = dict()
    
    # range gives as consecutive numbers from 0 to X-1
    # in this case, all valid indexes for the columns of the current line
    for i in range(len(lines_house_price)):
        
        # store each column value from the line using the column header we got before as key
        dict_house_price[key_house_price[i]] = lines_house_price[i]
    
    # add this lines information to the list of data
    house_price.append(dict_house_price)

# print collected data as output
print(house_price)
# (pretty formatted output):
#
# [{'land': ''},
#  {' building': ' 50',
#   ' distance_to_center': ' 15',
#   ' price': ' 500',
#   'land': '70'},
#  {'land': ''},
#  {' building': ' 60',
#   ' distance_to_center': ' 30',
#   ' price': ' 400',
#   'land': '70'},
#  {'land': ''},
#  {' building': ' 60',
#   ' distance_to_center': ' 55',
#   ' price': ' 300',
#   'land': '70'},
#  {'land': ''},
#  {' building': ' 50',
#   ' distance_to_center': ' 30',
#   ' price': ' 700',
#   'land': '100'},
#  {'land': ''},
#  {' building': ' 70',
#   ' distance_to_center': ' 25',
#   ' price': ' 1000',
#   'land': '100'},
#  {'land': ''},
#  {' building': ' 70',
#   ' distance_to_center': ' 50',
#   ' price': ' 650',
#   'land': '100'},
#  {'land': ''},
#  {' building': ' 100',
#   ' distance_to_center': ' 20',
#   ' price': ' 2000',
#   'land': '120'},
#  {'land': ''},
#  {' building': ' 80',
#   ' distance_to_center': ' 50',
#   ' price': ' 1200',
#   'land': '120'},
#  {'land': ''},
#  {' building': ' 100',
#   ' distance_to_center': ' 50',
#   ' price': ' 1800',
#   'land': '150'},
#  {'land': ''},
#  {' building': ' 90',
#   ' distance_to_center': ' 15',
#   ' price': ' 3000',
#   'land': '150'}]