如何解决如何将.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']}
解决方法
下面的代码虽然有点笨拙,但可以工作,也许您可以找到一个更好的解决方案,但是这个解决方案相当快。
#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
,
d = {}
with open('data.txt') as f:
for s in f.read().split('\n\n'):
lines = s.split('\n')
d[lines[0]] = lines[1:]
print(d)
这假设您的数据文件中没有换行符。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。