python-3.x - 如何将 .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
推荐阅读
- c++ - 使用指定路径从目录加载 PCD 文件(路径包含作为文件名的字符串)
- git - 在提交详细信息中搜索 Bitbucket 存储库中的评论
- swift - 获取视频数组的缩略图
- visual-studio-code - 并行安装 Visual Studio Code (vscode) 和 Visual Studio Code Insiders (vscode Insiders):修改标准应用
- import - 边缘数据未完全加载到 Neptune(通过 Python 和 Gremlin)
- codeigniter-3 - 我可以在 CodeIgniter Controller 中编写单个方法来处理 GET 和 POST 登录表单吗?
- c# - 如何根据租户动态更改资源路径(我们根据主机名确定租户)?
- java - 如何使用 cassandra java 驱动程序(3.6 版)在 Cassandra 访问器接口中传递分页状态?
- angular - 找不到名称“许多”-升级到 TypeScript 3.1.6
- c# - 在C#中计算数组元素的频率