2017年1月15日11:19:22
开始改写代码,使其通过字典进行存储并输出。
昨天的代码是将文件整个读入再输出,目前要使用字典来存储需要分两步进行:
- 将之前“整个文件读入/输出”更改为“逐行读取/输出”。
- 再将“逐行读取/输出”更改为“读取-->按字典存储-->输出”
逐行读取文件
犹记得《LPTHW》中的Exercise 16、17有读写的示例,所以我决定先复习下书中的例子。在Exercise 16当中提到了读取一行数据的readline函数,先改写代码,只读一行。
# -*- coding: utf-8 -*-
import sys
encoding_type = sys.getfilesystemencoding()
weather_info = open('weather_info.txt')
content = weather_info.readline()
print content.decode('utf-8').encode(encoding_type)
weather_info.close()
输出:
lianbche@5CG44636XG D:\Learning\git\Py103\Chap1\project
> python Coderound2_UseDict.py
北京,晴
接下来的问题便是怎样通过循环读取将整个文件读完,于是决定去阅读IdxPy103Reference当中的有关循环的参考链接:Looping Techniques。参考链接中用来做循环读取的示例是有关字典的,此时操作的是文件,因此直接在官方文档上索引到 文件对象,这里除了了解到如何循环读取文件之外,还又一次看到了with语句,并知晓了它的功能:自动调用文档对象的close操作。改写代码如下:
# -*- coding: utf-8 -*-
import sys
encoding_type = sys.getfilesystemencoding()
with open('weather_info.txt') as weather_info:
for line in weather_info:
print line.decode('utf-8').encode(encoding_type)
输出如下:
...
洛浦,晴
民丰,晴
于田,晴
阿勒泰,晴
哈巴河,晴间多云
吉木乃,晴间多云
布尔津,晴间多云
...
使用字典来存储数据
把天气数据转换为字典是当前子任务的主要内容。目前了解了字典,并且完成了逐行读取文件的操作,那么将读取的一行数据进行分析,再存储到字典当中便是下一步的工作。
查找了半天string的资料,还没有弄清楚如何将字符串当中的数据分离出来,当前自己的思路有以下几种:
- 直接通过格式化字符串,将其分离,类似于C语言当中的sprintf函数。
- 使用string当中的split函数来进行分离操作。
- 使用正则表达式。
看起来第一种最为简单,但现在却阻塞在这里。
好了,放弃第一种,使用第二种方法。写出代码:
# -*- coding: utf-8 -*-
import sys
encoding_type = sys.getfilesystemencoding()
with open('weather_info.txt') as weather_info:
for line in weather_info:
pair = line.split(',')
print pair[0].decode('utf-8').encode(encoding_type)
print pair[1].decode('utf-8').encode(encoding_type)
输出:
...
阿拉山口
晴
霍林郭勒
小雪
格尔木
晴间多云
都兰
晴间多云
柯桥
小雨
沙市
小雨
高力板
小雪
...
这样就可以将“城市”与“天气”都解析出来了。但怎样将它们存储到字典当中去呢?借助搜索引擎,查找到Python字典增删操作技巧简述,问题解决。修改源代码如下:
# -*- coding: utf-8 -*-
import sys
encoding_type = sys.getfilesystemencoding()
with open('weather_info.txt') as weather_info:
# Create one black dictionary to store weather data.
weather_report = {}
# Insert <city, weather> into dictionary.
for line in weather_info:
pair = line.split(',')
weather_report[pair[0]] = pair[1]
# Print cities in dictionary.
for city in weather_report.keys():
print city.decode('utf-8').encode(encoding_type)