首页 > 解决方案 > 如何将 .txt 文件写入 python 字典

问题描述

Name 1
car/machines
taxi
motorcycle

Name 2
address
phone number
age
education, school

Name 3
datetime
favorite

我想创建一个字典以将名称保存为键,并将名称下的详细信息保存为值。示例输出:

{'Name 1': ['car/machines', 'taxi', 'motorcycle'], 'Name 2': ['address', 'phone number', 'age', 'education, school'] 'Name 3': ['datetime', 'favorite']}

标签: python-3.xdictionarytext-files

解决方案


下面的代码虽然有点笨重,但可以工作,也许你可以找到更好的解决方案,但这个速度很快。

#Reading the text file
text = open('text.txt', 'r')
#Turning it into a list of lines
lines = text.readlines()
#Defining the last name variable
#For later use
last_name = str()
#Defining the dict
lines_dict = dict()
#The +1 is there because i need to append the list to the key
#At the last iteration
for x in range(len(lines)+1):
    #The try is here because it will overflow
    try:
        #Stripping the line of the newline character
        lines[x] = lines[x].strip()
        #Check if the 'Name' string is in the line in question
        if 'Name' in lines[x]:
            #If there is any last name
            if 'Name' in last_name:
                #Filter the dictionary of empty spaces
                temp_list = list(filter(None, temp_list))
                #Appends the value to the key in the dict
                lines_dict[last_name] = temp_list
            #Getting the last name
            last_name = lines[x]
            #Resseting the temp list
            temp_list = list()
        #If the string is not 'Name'
        else:
            #Append the string to the temp list
            temp_list.append(lines[x])
    #If it overflows
    except Exception as e:
        #Do the last appending
        lines_dict[last_name] = temp_list

推荐阅读