您的位置:首页 > 编程语言 > Python开发

python入门(六)查天气小程序(python3)

2018-02-28 22:14 211 查看
#coding=utf-8
from city import city
#若此处无法引用,则缺少#coding=utf-8
from urllib import request
#python3
import json

cityname = input("你想查哪个城市的天气?\n")
citycode = city.get(cityname)
if citycode:
try:
url = ("http://www.weather.com.cn/data/cityinfo/%s.html" % citycode)
page = request.urlopen(url).read().decode('utf-8')
content = str(page)
print(type(content))
data = json.loads(content)
print(type(data))
print(data)
result = data['weatherinfo']
str_temp = ('%s\n%s ~ %s') % (result['weather'], result['temp1'], result['temp2'])
print(str_temp)
except:
print("查询失败.")
else:
print("没有找到该城市")


以上程序中所用到的知识点如下:

#coding=utf-8
#位置:文件开头
#说明所使用的python文件编码
#'='必须和coding之间没有空格

from city import city
#从city.py中引用city内容

city.py
#存储城市对应代码的文件
#网上找来的资源:https://pan.baidu.com/s/1c0Nw4m

python3获取网页页面
#直接用urllib.request模块的urlopen()获取页面
网页数据格式
#网页的数据格式为bytes类型
#需要先用decode('utf-8')解码,再转换成str类型才能分析

type()方法
#查看括号内部内容的数据类型

json模块的loads()方法
用法:json.loads(字符串)
#将满足json格式的字符串转成字典
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python3 入门 快速 编程