python将txt文件读取为字典的示例

yipeiwu_com6年前Python基础

如下所示:

# -*- coding: utf-8 -*-
# @Time :18-8-2 下午3:23

import sys
reload(sys)
sys.setdefaultencoding('utf8')
fp = open("file", "r")
sample = fp.readlines()
result_list = [] # 创建一个空列表
with open('file', 'w') as f:
 for line in sample:
  result_dict = {}
  try:
   sample_ = line.split(' ')#按照空格进行文件中每一行的切割
   result_dict[sample_[0].split(':', 1)[0]] = sample_[0].split(':', 1)[1]#分别取:前后的数据为key和value
   result_dict[sample_[2].split(':', 1)[0]] = sample_[2].split(':', 1)[1]
   result_dict[sample_[4].split(':', 1)[0]] = sample_[4].split(':', 1)[1]
  except IndexError as s:
   pass
  result_list.append(result_dict)
 for i in result_list:
  data_value = str(i).decode('string_escape')#数据中存在中文字符,必须进行编码
  f.write(data_value)
  f.write('\n')

以上这篇python将txt文件读取为字典的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

matplotlib 纵坐标轴显示数据值的实例

实例如下所示: import matplotlib as mt import numpy as np y=[7,0,0,0,0,0,1,25,98,333,471,0,322,42...

在python3中pyqt5和mayavi不兼容问题的解决方法

在python3中pyqt5和mayavi不兼容问题的解决方法

环境: win10 64bit & Linux Mint 18.2 WinPython3.6.1,spyder,qtconsole iep3.7 问题描述: 通过http://www.l...

python中利用队列asyncio.Queue进行通讯详解

前言 本文主要给大家介绍了关于python用队列asyncio.Queue通讯的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。 asyncio.Queue与其...

pytorch 图像中的数据预处理和批标准化实例

目前数据预处理最常见的方法就是中心化和标准化。 中心化相当于修正数据的中心位置,实现方法非常简单,就是在每个特征维度上减去对应的均值,最后得到 0 均值的特征。 标准化也非常简单,在数据...

python 两个数据库postgresql对比

这篇文章主要介绍了python 两个数据库postgresql对比,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 比较两个postgr...