从txt文件创建字典的方法可以通过以下步骤实现:
以下是一个示例代码:
def create_dict_from_txt(file_path):
# 打开txt文件并读取内容
with open(file_path, 'r') as file:
content = file.read()
# 解析内容,提取关键年份和值列表
key_year = None
value_list = []
for line in content.split('\n'):
if line.startswith('年份'):
if key_year is not None:
# 将上一个关键年份和值列表添加到字典中
my_dict[key_year] = value_list
value_list = []
key_year = line.split(':')[1].strip()
else:
value_list.append(line.strip())
# 将最后一个关键年份和值列表添加到字典中
if key_year is not None:
my_dict[key_year] = value_list
return my_dict
# 调用函数创建字典
file_path = 'data.txt' # 替换为实际的txt文件路径
my_dict = create_dict_from_txt(file_path)
print(my_dict)
在上述代码中,我们首先打开txt文件并读取内容。然后,通过解析内容,按照关键年份和值列表的规则提取出数据。接下来,我们创建一个空字典,并将关键年份作为键,将值列表作为值,添加到字典中。最后,返回创建好的字典。
请注意,这只是一个示例代码,具体的解析规则可能需要根据实际的txt文件内容进行调整。同时,示例代码中的file_path
变量需要替换为实际的txt文件路径。
领取专属 10元无门槛券
手把手带您无忧上云