Crossin的编程教室

标题: 【Python 第45课】 查天气(3) [打印本页]

作者: crossin先生    时间: 2013-7-24 16:47
标题: 【Python 第45课】 查天气(3)
python 查天气系列:
【Python 第43课】 查天气(1) http://bbs.crossincode.com/forum.php?mod=viewthread&tid=8
【Python 第44课】 查天气(2) http://bbs.crossincode.com/forum.php?mod=viewthread&tid=9
【Python 第45课】 查天气(3) http://bbs.crossincode.com/forum.php?mod=viewthread&tid=12
【Python 第46课】 查天气(4) http://bbs.crossincode.com/forum.php?mod=viewthread&tid=42

看一下我们已经拿到的json格式的天气数据:
  1. {
  2.     "weatherinfo": {
  3.         "city": "南京",
  4.         "cityid": "101190101",
  5.         "temp1": "37℃",
  6.         "temp2": "28℃",
  7.         "weather": "多云",
  8.         "img1": "d1.gif",
  9.         "img2": "n1.gif",
  10.         "ptime": "11:00"
  11.     }
  12. }
复制代码
直接在命令行中看到的应该是没有换行和空格的一长串字符,这里我把格式整理了一下。可以看出,它像是一个字典的结构,但是有两层。最外层只有一个key--“weatherinfo”,它的value是另一个字典,里面包含了好几项天气信息,现在我们最关心的就是其中的temp1,temp2和weather。

虽然看上去像字典,但它对于程序来说,仍然是一个字符串,只不过是一个满足json格式的字符串。我们用python中提供的另一个模块json提供的loads方法,把它转成一个真正的字典。
  1. import json

  2. data = json.loads(content)
复制代码
这时候的data已经是一个字典,尽管在控制台中输出它,看上去和content没什么区别,只是编码上有些不同:
  1. {u'weatherinfo': {u'city': u'\u5357\u4eac', u'ptime': u'11:00', u'cityid': u'101190101', u'temp2': u'28\u2103', u'temp1': u'37\u2103', u'weather': u'\u591a\u4e91', u'img2': u'n1.gif', u'img1': u'd1.gif'}}
复制代码
但如果你用type方法看一下它们的类型:
  1. print type(content)
  2. print type(data)
复制代码
就知道区别在哪里了。

之后的事情就比较容易了。
  1. result = data['weatherinfo']
  2. str_temp = ('%s\n%s ~ %s') % (
  3.     result['weather'],
  4.     result['temp1'],
  5.     result['temp2']
  6. )
  7. print str_temp
复制代码
为了防止在请求过程中出错,我加上了一个异常处理。
  1. try:
  2.     ###
  3.     ###
  4. except:
  5.     print '查询失败'
复制代码
以及没有找到城市时的处理:
  1. if citycode:
  2.     ###
  3.     ###
  4. else:
  5.     print '没有找到该城市'
复制代码
45.png

完整代码:
  1. # -*- coding: utf-8 -*-
  2. import urllib2
  3. import json
  4. from city import city

  5. cityname = raw_input('你想查哪个城市的天气?\n')
  6. citycode = city.get(cityname)
  7. if citycode:
  8.     try:
  9.         url = ('http://www.weather.com.cn/data/cityinfo/%s.html'
  10.                % citycode)
  11.         content = urllib2.urlopen(url).read()
  12.         data = json.loads(content)
  13.         result = data['weatherinfo']
  14.         str_temp = ('%s\n%s ~ %s') % (
  15.             result['weather'],
  16.             result['temp1'],
  17.             result['temp2']
  18.         )
  19.         print str_temp
  20.     except:
  21.         print '查询失败'
  22. else:
  23.     print '没有找到该城市'
复制代码
#==== Crossin的编程教室 ====#
微信ID:crossincode
QQ群:312723402

面向零基础初学者的编程课
每天5分钟,轻松学编程



作者: byron    时间: 2013-7-24 19:24
Cool

限制字节。。。
作者: crossin先生    时间: 2013-7-24 19:28
byron 发表于 2013-7-24 19:24
Cool

限制字节。。。

嗯,去掉限制了
作者: 浮生湮灭了美好    时间: 2013-7-24 21:44
来了
作者: crossin先生    时间: 2013-7-24 21:47
浮生湮灭了美好 发表于 2013-7-24 21:44
来了


作者: jeeyoo    时间: 2013-7-24 22:25
来顶一顶!
作者: crossin先生    时间: 2013-7-24 23:02
jeeyoo 发表于 2013-7-24 22:25
来顶一顶!


作者: feicien    时间: 2013-7-24 23:28
论坛还没有人气
作者: crossin先生    时间: 2013-7-24 23:43
feicien 发表于 2013-7-24 23:28
论坛还没有人气

嗯,昨天刚刚小范围公布,还没多少人来。人气还要靠大家
作者: cyin15288    时间: 2013-7-25 11:02
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 326, in loads
    return _default_decoder.decode(s)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: expected string or buffer
现在反而查询不到了!试了一下是在datas=json.loads(content)出得错,从命令行试了一下报上面的错误!
作者: crossin先生    时间: 2013-7-25 11:14
cyin15288 发表于 2013-7-25 11:02
Traceback (most recent call last):
  File "", line 1, in
  File "/System/Library/Frameworks/Python. ...

把content打出来看看
作者: cyin15288    时间: 2013-7-25 11:42
crossin先生 发表于 2013-7-25 11:14
把content打出来看看

我又重新写了一个文件,发现可以了!
作者: lwolf    时间: 2013-7-25 23:02
Traceback (most recent call last):
  File "lesson43_weather.py", line 4, in <module>
    from city import city
  File "/home/lwolf/python/city.py", line 2
SyntaxError: Non-ASCII character '\xe5' in file /home/lwolf/python/city.py on line 2, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details
出现这个错误啦
作者: crossin先生    时间: 2013-7-26 14:32
cyin15288 发表于 2013-7-25 11:02
Traceback (most recent call last):
  File "", line 1, in
  File "/System/Library/Frameworks/Python. ...

看上去,像是没有请求成功,没拿到json数据。你把content输出看看,我估计是空的,或者错误代码
作者: wh555s    时间: 2013-7-26 22:26
crossin先生 发表于 2013-7-24 19:28
嗯,去掉限制了

先生你好,最近开始接触Django,但是不知道怎样开始正确的安装,我已经安装python2.7.5并使用一段时间,希望先生能闲暇之余贴一个安装使用Django的帖子以解燃眉之急!非常感谢~(另:昨天刚刚安装了PostgreSQL...)
作者: crossin先生    时间: 2013-7-27 00:51
wh555s 发表于 2013-7-26 22:26
先生你好,最近开始接触Django,但是不知道怎样开始正确的安装,我已经安装python2.7.5并使用一段时间, ...

那可得等我下周回来了,我也正打算讲一下django
作者: wh555s    时间: 2013-7-27 16:54
crossin先生 发表于 2013-7-27 00:51
那可得等我下周回来了,我也正打算讲一下django

好的好的,真是雪中送炭!祝先生旅途愉快~
作者: simple    时间: 2013-7-29 16:45
Traceback (most recent call last):
  File "D:\Py\test\weather.py", line 10, in <module>
    from city import city
  File "D:\Py\test\city.py", line 1
SyntaxError: Non-ASCII character '\xb1' in file D:\Py\test\city.py on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details
>>>
这个错误。能给个思路吗。是说编码格式不对吗

作者: simple    时间: 2013-7-29 16:49
是把content打印出来吗。。貌似没反应
作者: crossin先生    时间: 2013-7-29 23:12
simple 发表于 2013-7-29 16:45
Traceback (most recent call last):
  File "D:\Py\test\weather.py", line 10, in
    from city import ...

在city文件的第一行加上coding:utf8那句,或者下载本帖附件中的city.py
作者: w5132008    时间: 2013-8-1 22:02
代码成功!好奇如何输出图片
作者: crossin先生    时间: 2013-8-5 16:24
w5132008 发表于 2013-8-1 22:02
代码成功!好奇如何输出图片

控制台没办法输出图片,想输出图片的话,要用到图形界面
作者: 文书    时间: 2013-9-2 21:07
先生,你能讲解下json吗?这个不是很明白
作者: crossin先生    时间: 2013-9-3 10:49
文书 发表于 2013-9-2 21:07
先生,你能讲解下json吗?这个不是很明白

简单来说,json就是一种文本格式,有点像xml的意思,本质上是一个字符串。这个字符串用来表示一组数据。它数据的组织形式又很像python中的字典,是按照{"名称":"值","名称":"值"}的形式来的。有了这种约定好的形式之后,把数据转换成字符串传递就比较方便了
作者: wolfl    时间: 2013-9-11 09:29
Traceback (most recent call last):
  File "C:\Python27\program\lesson43_weather.py", line 4, in <module>
    from city import city
  File "C:\Python27\program\city.py", line 2
SyntaxError: Non-ASCII character '\xb1' in file C:\Python27\program\city.py on line 2, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details
>>> 这是怎么回事,试了很多编了,求帮助啊,大仙们!
作者: crossin先生    时间: 2013-9-11 11:59
wolfl 发表于 2013-9-11 09:29
Traceback (most recent call last):
  File "C:\Python27\program\lesson43_weather.py", line 4, in
    ...

你是windows吧,在city.py开头的coding里面改成cp936试试
作者: 羽扇纶巾    时间: 2013-9-27 18:05
请教一下,我想输出玩结果之后可以立即输入下一个城市返回结果,应该怎么写?
作者: crossin先生    时间: 2013-9-27 21:08
羽扇纶巾 发表于 2013-9-27 18:05
请教一下,我想输出玩结果之后可以立即输入下一个城市返回结果,应该怎么写? ...

外面加一层while
参照 猜数字游戏
作者: 阿努比斯    时间: 2013-10-8 23:36
本帖最后由 阿努比斯 于 2013-10-8 23:40 编辑

[attach]191[/attach]
先生您好,我是仿照您的编码来实现了这个查天气功能,但是发现总是"查询失败",不知道是什么原因。输出result['weather']、result['temp1']、result['temp2']都没有问题,不知道是怎么回事,求解答。

QQ截图20131008233808.png (24.02 KB, 下载次数: 341)

QQ截图20131008233808.png


作者: crossin先生    时间: 2013-10-9 00:33
把输出结果和错误提示一并发上来看看
作者: crossin先生    时间: 2013-10-9 00:34
阿努比斯 发表于 2013-10-8 23:36
先生您好,我是仿照您的编码来实现了这个查天气功能,但是发现总是"查询失败",不知道是什么原因。输出result ...

把输出和错误提示一并发上来看看
作者: 哎哟薇    时间: 2013-10-17 01:09
可以,就是手太新了,看不懂,但是有兴趣,明天来搞懂这个查天气。顶,
作者: liu-pengfei    时间: 2014-9-25 15:09
import urllib2
import json

web = urllib2.urlopen('http://www.baidu.com')
content = web.read()
html = file('baidu.html','w')
html.write(content)
html.close()
print type(content)

data = json.loads(content)
print type(data)

先生,这些代码倒数第二句总是报错,说是解析不了。ValueError: No JSON object could be decoded.
不知道改什么东西?
作者: liu-pengfei    时间: 2014-9-25 15:25
本帖最后由 liu-pengfei 于 2014-9-25 16:04 编辑

先生,还有问题,我复制了你的代码,执行的时候无论输入哪个城市,总是输出没有找到该城市。我调试,发现if后面的语句不会执行,不知道为什么?

我有查到,原来是编码的问题。都是# -*- coding: cp936 -*-在捣乱,原来没有看清先生的讲解啊。

作者: csyhhb    时间: 2015-5-15 11:32
str_temp = ('%s\n%s ~ %s') % (
            result['weather'],
            result['temp1'],
            result['temp2']
        )
为什么我在('%s\n%s ~ %s')里面一加中文就会报错?
作者: crossin先生    时间: 2015-5-17 00:45
csyhhb 发表于 2015-5-15 11:32
str_temp = ('%s\n%s ~ %s') % (
            result['weather'],
            result['temp1'],

如果是中文,会触发一次unicode到str的转换,但默认的编码不支持中文
你如改成 u('%s\n%s ~ %s') % (...) 大概就可以了
作者: csyhhb    时间: 2015-5-17 14:03
crossin先生 发表于 2015-5-17 00:45
如果是中文,会触发一次unicode到str的转换,但默认的编码不支持中文
你如改成 u('%s\n%s ~ %s') % (...) ...

确实是里面的编码不一致就不会输出了 我把 result['weather']改成 result['weather'].encode('utf-8')也可以
作者: 我是佩佩学姐    时间: 2015-11-12 12:19
本帖最后由 我是佩佩学姐 于 2015-11-12 13:54 编辑

Crossin先生,我是问题少年~又来求问,我把评论里的问题都找过了没法解决才提问的,出现以下问题:
1、if....else这块出问题,会提示:EOL While scanning string literal,必须把else语句去掉程序才可以正常执行
2、去掉else 之后,程序执行结果一直显示‘查询失败’,print result 结果正常。求老师指点
Idle 结果:
你想查询哪个城市的天气?
福州
101230101
http://www.weather.com.cn/data/cityinfo/101230101.html
{"weatherinfo":{"city":"福州","cityid":"101230101","temp1":"30℃","temp2":"18℃","weather":"多云","img1":"d1.gif","img2":"n1.gif","ptime":"08:00"}}
<type 'str'>
<type 'dict'>
{u'city': u'\u798f\u5dde', u'ptime': u'08:00', u'cityid': u'101230101', u'temp2': u'18\u2103', u'temp1': u'30\u2103', u'weather': u'\u591a\u4e91', u'img2': u'n1.gif', u'img1': u'd1.gif'}
  1. # -*- coding: cp936 -*-
  2. import urllib2
  3. import json
  4. from city import city


  5. cityname = raw_input('你想查询哪个城市的天气?\n')
  6. citycode = city.get(cityname)
  7. print citycode
  8. if citycode:
  9.     try:
  10.         url = ('http://www.weather.com.cn/data/cityinfo/%s.html'%citycode)
  11.         print url
  12.         content=urllib2.urlopen(url).read()
  13.         print content

  14.         data = json.loads(content)

  15.         print type(content)
  16.         print type(data)
  17.         result = data['weatherinfo']
  18.         print result                      #测试result
  19.         str_temp = u'%s\n%s~%s'%(result['weather'],result['temp1'],result['temp2'])
  20.         print str_temp
  21.     except:
  22.         print '查询失败'
  23. else:
  24.     print '没有找到该城市’
复制代码

作者: crossin先生    时间: 2015-11-12 13:03
我是佩佩学姐 发表于 2015-11-12 12:19
Crossin先生,我是问题少年~又来求问,我把评论里的问题都找过了没法解决才提问的,出现以下问题:
1、if... ...

前一个问题是你最后一个引号不对吧,是中文引号
后面一个是,unicode直接%s转的话,会默认用ascii,所以中文会有问题。你试试看用 + 来拼字符串而不用 %s。或者改成result['weather'].encode('utf8')
作者: 我是佩佩学姐    时间: 2015-11-12 13:57
crossin先生 发表于 2015-11-12 13:03
前一个问题是你最后一个引号不对吧,是中文引号
后面一个是,unicode直接%s转的话,会默认用ascii,所以 ...

谢谢先生~查天气(1)-(3)的问题都解决了哈。
作者: 周末晒被子    时间: 2015-12-10 12:36
Crossin先生,
result = data['weatherinfo']
这一句,是 result[n]==data['weatherinfo[n]'] 这样的意思吗?
作者: crossin先生    时间: 2015-12-10 21:35
周末晒被子 发表于 2015-12-10 12:36
Crossin先生,
result = data['weatherinfo']
这一句,是 result[n]==data['weatherinfo[n]'] 这样的意思吗 ...

不是啊,这就是一个赋值语句,把data['weatherinfo']的值保存在result里
你下面那句是个比较两个值的语句
作者: 周末晒被子    时间: 2015-12-10 21:46
本帖最后由 周末晒被子 于 2015-12-10 21:47 编辑
crossin先生 发表于 2015-12-10 21:35
不是啊,这就是一个赋值语句,把data['weatherinfo']的值保存在result里
你下面那句是个比较两个值的语句 ...

表达有误....我是想表达result[n]是不是实质上相当于data['weatherinfo[n]'] ?

看了老师的回复,result = data['weatherinfo']之后,result已经变成一个字典了吧。
作者: crossin先生    时间: 2015-12-11 21:52
周末晒被子 发表于 2015-12-10 21:46
表达有误....我是想表达result[n]是不是实质上相当于data['weatherinfo[n]'] ?

看了老师的回复,result  ...

result[n] 相当于data['weatherinfo'][n]
作者: 周末晒被子    时间: 2015-12-12 13:04
crossin先生 发表于 2015-12-11 21:52
result[n] 相当于data['weatherinfo'][n]

对!谢谢先生!
作者: Kunz    时间: 2015-12-24 18:11
Traceback (most recent call last):
  File "<string>", line 83, in run
  File "C:\Python34\lib\bdb.py", line 431, in run
    exec(cmd, globals, locals)
  File "C:\Python34\Doc\p45.py", line 2, in <module>
    import urllib.request
  File "C:\Python34\lib\urllib\request.py", line 161, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Python34\lib\urllib\request.py", line 469, in open
    response = meth(req, response)
  File "C:\Python34\lib\urllib\request.py", line 579, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Python34\lib\urllib\request.py", line 507, in error
    return self._call_chain(*args)
  File "C:\Python34\lib\urllib\request.py", line 441, in _call_chain
    result = func(*args)
  File "C:\Python34\lib\urllib\request.py", line 587, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 404: Not Found

这是什么问题?有没有可能是电脑网络的问题?
作者: crossin先生    时间: 2015-12-24 21:48
Kunz 发表于 2015-12-24 18:11
Traceback (most recent call last):
  File "", line 83, in run
  File "C:\Python34\lib\bdb.py", line  ...

网页失效了
作者: Kunz    时间: 2015-12-25 12:07
crossin先生 发表于 2015-12-24 21:48
网页失效了

确实是,时好时坏的~~
作者: pypr    时间: 2016-1-18 23:01
为什么一直是查询失败啊
作者: crossin先生    时间: 2016-1-19 10:54
pypr 发表于 2016-1-18 23:01
为什么一直是查询失败啊

链接失效了吧。看一下查天气(1)开头的说明和链接
作者: catherinemic    时间: 2016-1-22 19:56
今天一切顺利~~
关于编码的问题,自己看了一些文章,大致有一些了解,但还是有一个问题想请教crossin先生:
我看到说python内部使用unicode编码,为什么从json.loads之后,data字典里面把原来content里面的内容都加u'xxx'了呢?是因为content是json格式,python处理的时候要先自动转成unicode格式,而且还要这样显示出来吗?这样,后面要访问data里某个键对应的值的时候,就不用再在内容前面加u'xxx'了?
  1. # -*- coding: cp936 -*-
  2. import urllib2
  3. import json
  4. from city import city
  5. cityname=raw_input("Which city's weather do you want to know?\n")
  6. citycode=city.get(cityname)
  7. print citycode
  8. if citycode:
  9.     try:
  10.         url='http://www.weather.com.cn/data/cityinfo/%s.html'%citycode
  11.         print url
  12.         content=urllib2.urlopen(url).read()
  13.         print content
  14.         data=json.loads(content)
  15.         print data
  16.         print type(content)
  17.         print type(data)
  18.         result=data['weatherinfo']
  19.         str_temp='%s\n%s - %s'%(result['weather'],result['temp1'],result['temp2'])
  20.         print str_temp
  21.     except:
  22.         print 'Query failure.'
  23. else:
  24.     print "Couldn't find the city."
复制代码

Python25.png (19.45 KB, 下载次数: 294)

Python25.png


作者: crossin先生    时间: 2016-1-23 11:13
catherinemic 发表于 2016-1-22 19:56
今天一切顺利~~
关于编码的问题,自己看了一些文章,大致有一些了解,但还是有一个问题想请教crossin先生: ...

单独print某个字符串值的时候,print会帮你默认做一次编码。而在list或者dict中直接print,不会对每一个元素解码,只会保持原本的样子
作者: catherinemic    时间: 2016-1-23 12:08
本帖最后由 catherinemic 于 2016-1-23 12:09 编辑
crossin先生 发表于 2016-1-23 11:13
单独print某个字符串值的时候,print会帮你默认做一次编码。而在list或者dict中直接print,不会对每一个 ...

这里大概明白了,谢谢crossin老师~
那为什么在访问dict的时候,只用写result['weather'],而不用result[u'weather']呢?
作者: crossin先生    时间: 2016-1-24 10:04
catherinemic 发表于 2016-1-23 12:08
这里大概明白了,谢谢crossin老师~
那为什么在访问dict的时候,只用写result['weather'],而不用result呢 ...

也是程序默认做了转换
作者: catherinemic    时间: 2016-1-24 15:35
crossin先生 发表于 2016-1-24 10:04
也是程序默认做了转换

这样啊,谢啦~
作者: 王大锤    时间: 2016-3-4 12:57
/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /Users/hammer/Desktop/try.py
  File "/Users/hammer/Desktop/try.py", line 6
SyntaxError: Non-ASCII character '\xe4' in file /Users/hammer/Desktop/try.py on line 6, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

我的出现了这个错误

P.S. 我的city文件和代码文件的开头都加上了 # -*- coding:utf-8 -*-
作者: crossin先生    时间: 2016-3-4 13:47
王大锤 发表于 2016-3-4 12:57
/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /Users/hammer/Desktop/try.py
...

try.py 没有申明编码类型。你再确认一下吧,或者改成#coding:cp936 试试看
作者: crossin先生    时间: 2016-3-4 13:48
王大锤 发表于 2016-3-4 12:57
/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /Users/hammer/Desktop/try.py
...

另外不要用python的保留字来命名自己的文件或方法、变量等,不然可能会出问题,try本身已有用法。
作者: 王大锤    时间: 2016-3-5 00:34
crossin先生 发表于 2016-3-4 13:48
另外不要用python的保留字来命名自己的文件或方法、变量等,不然可能会出问题,try本身已有用法。 ...

谢谢先生
作者: 王大锤    时间: 2016-3-5 00:41
先生,已经把文件名从try改成lesson43,可是错误还是没有变化 屏幕快照 2016-03-05 上午12.40.02.png
作者: vincent1456    时间: 2016-3-5 10:06
Traceback (most recent call last):
  File "C:\Users\admin\py实验\weather\weather.py", line 16, in <module>
    data=json.loads(content)
  1. from urllib import request
  2. from city import city

  3. print('你想查询哪个城市的天气?')
  4. cityname=input()
  5. citycode=city.get(cityname)
  6. if citycode:
  7.    
  8.     url = 'http://www.weather.com.cn/data/cityinfo/%s.html' % citycode
  9.     web=request.urlopen(url)
  10.     content=str(web.read())
  11.     print(type(content))
  12.     print(content)

  13.     import json
  14.     data=json.loads(content)
  15.     print(data)
复制代码
File "C:\Python34\lib\json\__init__.py", line 318, in loads
    return _default_decoder.decode(s)
  File "C:\Python34\lib\json\decoder.py", line 343, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Python34\lib\json\decoder.py", line 361, in raw_decode
    raise ValueError(errmsg("Expecting value", s, err.value)) from None
ValueError: Expecting value: line 1 column 1 (char 0)
作者: crossin先生    时间: 2016-3-5 10:30
vincent1456 发表于 2016-3-5 10:06
Traceback (most recent call last):
  File "C:%users\admin\py实验\weather\weather.py", line 16, in
  ...

content好像是none没取到值。你确认下每一步的值。你用的python3吧,可能有些函数用法不一样
作者: crossin先生    时间: 2016-3-5 10:35
王大锤 发表于 2016-3-5 00:41
先生,已经把文件名从try改成lesson43,可是错误还是没有变化

第一行coding没起作用,你是不是用了中文冒号。或者你这个编辑器有其它编码设置。不行换个编辑器试下。还有你下面的缩进不对
作者: vincent1456    时间: 2016-3-5 10:59
crossin先生 发表于 2016-3-5 10:30
content好像是none没取到值。你确认下每一步的值。你用的python3吧,可能有些函数用法不一样 ...

是的,python3有很多不懂的地方也查不到教程,为了更好地学习,现在已经换成了python27,谢谢您!
作者: yjw413    时间: 2016-3-7 20:45
  1. # -*- coding:cp936 -*-
  2. import urllib.request
  3. import json
  4. from city import city

  5. cityname = input('你想查询哪个城市?\n')
  6. citycode = city.get(cityname)
  7. if citycode:
  8.     try:
  9.         url = ('http://www.weather.com.cn/data/cityinfo/%s.html'%citycode)
  10.         content = urllib.request.urlopen(url).read()
  11.         data = json.loads(content.decode('utf-8'))
  12.         result = data['weatherinfo']
  13.         str_temp = ('%s\n%s~%s')%(
  14.                 result['weather'],
  15.                 result['temp1'],
  16.                 result['temp2']
  17.                 )
  18.         print(str_temp)
  19.     except:
  20.         print('查询失败')
  21. else:
  22.     print('你所查询的城市不存在!')
复制代码

作者: hefengair    时间: 2016-3-21 11:50
python中'' 和None的区别是什么
如何看一个方法的返回值

        citycode = city.get(cityname)
        if citycode == None: #if citycode == ''   
        city.get()的返回值是什么
作者: crossin先生    时间: 2016-3-21 12:35
hefengair 发表于 2016-3-21 11:50
python中'' 和None的区别是什么
如何看一个方法的返回值

None是专门的空值,''有值,只是这个值是空字符。
程序如何判断,要看你需要判断什么。这里get方法如果取不到值会返回None,所以你应该判断None。
另外,也可以直接用
if citycode:
因为不管None还是'',它们转成bool值都是False
作者: AvyMiz    时间: 2016-5-1 10:52
先生你好,
debug时我发现程序在
data = json.loads(content)
会出现错误。
错误报告:ValueError: No JSON object could be decoded
经检查是由于content的内容出现了乱码,即没有出现应有的字典型的数据。
困扰我的一点是这个错误出现的原因我不清楚,有时候我只是改了一个变量程序又会正常运行,请问content出现乱码的原因是什么呢?该如何解决这个问题呢?
作者: chuifeng    时间: 2016-5-1 13:52
好奇怪,查询杭州、天津可以,北京、上海却查询失败,用的是先生的city.py
作者: crossin先生    时间: 2016-5-1 22:05
AvyMiz 发表于 2016-5-1 10:52
先生你好,
debug时我发现程序在
data = json.loads(content)

部分中文乱码是编码问题,要手动解码。全乱码可能是网站用了gzip压缩,需要解压,见这里:http://bbs.crossincode.com/forum ... amp;page=13#pid9075
作者: crossin先生    时间: 2016-5-1 22:07
chuifeng 发表于 2016-5-1 13:52
好奇怪,查询杭州、天津可以,北京、上海却查询失败,用的是先生的city.py

把中间的结果都打印出来,确定问题所在,是直辖市的页面地址不对,还是请求出来的结果不对。
作者: Joshtu    时间: 2016-6-28 17:01
为啥查询的天气结果,和直接在中国天气网上查询的,相差很远呢?重庆
阴转阵雨
21℃ ~ 17℃
实际结果:22 ~ 28°C。
作者: crossin先生    时间: 2016-6-29 14:28
Joshtu 发表于 2016-6-28 17:01
为啥查询的天气结果,和直接在中国天气网上查询的,相差很远呢?重庆
阴转阵雨
21℃ ~ 17℃

我也发现了,这个接口好像数据是假的。参考下第一课里面给的新接口
作者: Joshtu    时间: 2016-6-29 17:31
crossin先生 发表于 2016-6-29 14:28
我也发现了,这个接口好像数据是假的。参考下第一课里面给的新接口

好的!谢谢您
作者: sunbaodi    时间: 2016-9-20 21:55
因为用的是notepad++的编辑器,尝试着如crossin先生说的一样编码直接设置成gbk,但是没有成功。运行总是显示查询失败,后来尝试打印出每个步骤的结果,然后查资料找了json的loads使用注意事项找出了原因,就是如果传入json的字符串不是utf-8编码的话,就无法调用json的loads方法,因为前面content只有转换成gbk才能显示,所以这一步要指定字符编码。编码如下:
  1. # -*- coding:utf-8 -*-
  2. import urllib2
  3. import json
  4. from city import city

  5. cityname = raw_input('你想查哪里城市的天气?\n'.decode('utf-8').encode('gbk'))
  6. citycode = city.get(cityname.decode('gbk').encode('utf-8'))
  7. if citycode:
  8.         try:
  9.                 url = ('http://www.weather.com.cn/data/cityinfo/%s.html' % citycode)
  10.                 content = urllib2.urlopen(url).read().decode('utf-8').encode('gbk')
  11.                 data = json.loads(content,encoding = 'gbk')
  12.                 result = data['weatherinfo']
  13.                 str_temp = ('%s\n%s ~ %s') % (result['weather'], result['temp1'], result['temp1'])
  14.                 print str_temp
  15.         except:
  16.                 print u'查询失败'
  17. else:
  18.         print u'没有找到该城市'
复制代码

作者: swinh    时间: 2016-10-7 19:24
# -*- coding:cp936 -*-
import urllib.request
import json
from city import city

cityname = input('你想查询哪个城市?\n')
citycode = city.get(cityname)
if citycode:
    try:
        url = ('http://wthrcdn.etouch.cn/weather_mini?citykey=%s'%citycode)
        content = urllib.request.urlopen(url).read()
        data = json.loads(content.decode('utf-8'))
        result = data['weatherinfo']
        str_temp = ('%s\n%s~%s')%(
                result['weather'],
                result['temp1'],
                result['temp2']
                )
        print(str_temp)
    except:
        print('查询失败')
else:
    print('你所查询的城市不存在!')
老师,更换网址后显示查询失败,是什么回事呢?网址不对?
作者: crossin先生    时间: 2016-10-8 09:50
swinh 发表于 2016-10-7 19:24
# -*- coding:cp936 -*-
import urllib.request
import json

你把请求的网址print出来,放浏览器里看对不对

作者: James_Danni    时间: 2017-7-19 16:44
result = data['weatherinfo']
这一句的作用是什么
作者: crossin先生    时间: 2017-7-19 22:43
James_Danni 发表于 2017-7-19 16:44
result = data['weatherinfo']
这一句的作用是什么

你看下data的内容就知道了。这是字典的基本操作,取 weatherinfo 这个键对应的值
作者: snake-zzp    时间: 2017-8-4 22:09
啊,来的有点晚啊,都这么久的帖子了
作者: snake-zzp    时间: 2017-8-4 22:10
不过我刚刚完成,还是良心啊
作者: 无知少男    时间: 2017-8-14 11:26
楼主你好,我的代码按照你的抄了一遍,为啥不成功,我把云盘city.py 文件与代码文件放在一个文件夹下
结果显示Traceback (most recent call last):
  File "F:/python练习/9/9.py", line 4, in <module>
    from city import city
  File "F:/python练习/9\city.py", line 2
SyntaxError: Non-ASCII character '\xe5' in file F:/python练习/9\city.py on line 2, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

作者: crossin先生    时间: 2017-8-14 19:45
无知少男 发表于 2017-8-14 11:26
楼主你好,我的代码按照你的抄了一遍,为啥不成功,我把云盘city.py 文件与代码文件放在一个文件夹下
结果 ...

代码第一行要加上
  1. #coding: gbk
复制代码
两个文件都要加
作者: blueheart    时间: 2017-8-24 14:12
哈哈,我把字符串转换成字典成功了
查看天气3.png
作者: blueheart    时间: 2017-8-24 14:30

把字符串转换成字典.png
作者: blueheart    时间: 2017-8-24 14:39
本帖最后由 blueheart 于 2017-8-24 14:50 编辑
  1. # -*- coding: UTF-8 -*-
  2. import urllib2
  3. import json
  4. from city import city

  5. cityname = raw_input('你想查哪个城市的天气?\n'.decode('utf-8').encode('gbk'))
  6. print
  7. citycode = city.get(cityname.decode('gbk').encode('utf-8'))
  8. if citycode:
  9.         url = ('http://www.weather.com.cn/data/cityinfo/%s.html'%citycode)
  10.         print url
  11.         content = urllib2.urlopen(url).read().decode('utf-8').encode('gbk')
  12.         content1 = urllib2.urlopen(url).read()
  13.         data = json.loads(content1)
  14.         print type(content)
  15.         print type(data)
  16.         print data
  17.         print content
  18.         result = data['weatherinfo']
  19.         str_temp = ('%s\n%s ~ %s') % (
  20.             result['weather'],
  21.             result['temp1'],
  22.             result['temp2']

  23.         )
  24.         print str_temp
复制代码

摘取字典的字段.png (89.76 KB, 下载次数: 222)

摘取字典的字段.png


作者: blueheart    时间: 2017-8-24 15:39
本帖最后由 blueheart 于 2017-8-24 15:59 编辑
  1. # -*- coding: UTF-8 -*-
  2. import urllib2
  3. import json
  4. from city import city

  5. cityname = raw_input('你想查哪个城市的天气?\n'.decode('utf-8').encode('gbk'))
  6. citycode = city.get(cityname.decode('gbk').encode('utf-8'))
  7. if citycode:
  8.     try:
  9.         url = ('http://www.weather.com.cn/data/cityinfo/%s.html'%citycode)
  10.         print url
  11.         content = urllib2.urlopen(url).read().decode('utf-8').encode('gbk')
  12.         content1 = urllib2.urlopen(url).read()
  13.         data = json.loads(content1)
  14.         print type(content)
  15.         print type(data)
  16.         print data
  17.         print content
  18.         result = data['weatherinfo']
  19.         print result
  20.         str_temp = ('%s\n%s ~ %s') % (
  21.             result['weather'],
  22.             result['temp1'],
  23.             result['temp2']

  24.         )
  25.         print str_temp
  26.     except:
  27.             print '查询失败'
  28. else:
  29.     print '没有找到该城市'
复制代码

异常判断.png (110.01 KB, 下载次数: 216)

异常判断.png

异常判断1.png (19.15 KB, 下载次数: 218)

异常判断1.png

查询失败.png (97.72 KB, 下载次数: 217)

查询失败.png


作者: chchch0720    时间: 2017-9-21 10:04
  1. # -*- coding: cp936 -*-
  2. import urllib2
  3. import json
  4. from city import city

  5. cityname = raw_input('你想查哪个城市的天气?\n')
  6. citycode = city.get(cityname)
  7. if citycode:
  8.         try:
  9.                 url = ('http://www.weather.com.cn/data/cityinfo/%s.html'
  10.                        % city_code)
  11.                 content = urllib2.urlopen(url).read()
  12.                 data = json.loads(content)
  13.                 result = data['weatherinfo']
  14.                 str_temp = ('%s\n%s ~ %s')%(
  15.                         result['weather'],
  16.                         result['temp1'],
  17.                         result['tmep2']
  18.                 )
  19.                 print str_temp
  20.         except:
  21.                 print '查询失败'
  22. else:
  23.         print '没有找到该城市'
复制代码
  1. Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
  2. Type "copyright", "credits" or "license()" for more information.
  3. >>> ================================ RESTART ================================
  4. >>>
  5. 你想查哪个城市的天气?
  6. 北京
  7. 查询失败
  8. >>> ================================ RESTART ================================
  9. >>>
  10. 你想查哪个城市的天气?
  11. 西安
  12. 查询失败
  13. >>> ================================ RESTART ================================
  14. >>>
  15. 你想查哪个城市的天气?
  16. 什么鬼
  17. 没有找到该城市
  18. >>>
复制代码

作者: chchch0720    时间: 2017-9-21 10:05
chchch0720 发表于 2017-9-21 10:04

先生,city.py我用的您的代码,前面也加过了cp936
作者: crossin先生    时间: 2017-9-21 13:50
chchch0720 发表于 2017-9-21 10:05
先生,city.py我用的您的代码,前面也加过了cp936

应该不是编码问题
把 try...except 去掉,或者在except里输出报错信息,看看报什么错。不然报错都被你的异常处理覆盖掉了,没法看出来什么问题
作者: chchch0720    时间: 2017-9-22 09:15
crossin先生 发表于 2017-9-21 13:50
应该不是编码问题
把 try...except 去掉,或者在except里输出报错信息,看看报什么错。不然报错都被你的 ...

Traceback (most recent call last):
  File "C:\Python27\Crossin\44weather.py", line 18, in <module>
    result['tmep2']
KeyError: 'tmep2'

应该用get嘛?
作者: woodumpling    时间: 2017-9-22 09:34
这个报错告诉你没有这个键。。可以尝试用get来回避报错,但还是要弄清楚键名是什么才能取到想要的内容
作者: crossin先生    时间: 2017-9-22 22:48
chchch0720 发表于 2017-9-22 09:15
Traceback (most recent call last):
  File "C:\Python27\Crossin\44weather.py", line 18, in
    res ...

那个键好像是 temp2
作者: asphodelus    时间: 2017-11-2 12:29
本帖最后由 asphodelus 于 2017-11-2 12:34 编辑

py3似乎不少用法都和py2不一样了,raw_input,urllib等等
为了测试方便,去掉了try except添加打印content
改成content = urllib.request.urlopen(url).read().decode()
json解码问题似乎就解决了,不确定这么做是否一直有效,烦请先生来指点一下~附上截图






1.png (11.67 KB, 下载次数: 207)

1.png

2.png (14.49 KB, 下载次数: 212)

2.png

3.png (10 KB, 下载次数: 213)

3.png


作者: crossin先生    时间: 2017-11-2 13:04
asphodelus 发表于 2017-11-2 12:29
py3似乎不少用法都和py2不一样了,raw_input,urllib等等
为了测试方便,去掉了try except添加打印content
...

你做的是对的

你也可以用 requests 库,可以省很多事
作者: lubvi    时间: 2017-11-6 17:48
整合了这两课的内容,小小修改了一下
  1. import urllib.request
  2. import json
  3. from city import city

  4. exit=False

  5. while not exit:
  6.     cityname=input("你想查询哪个城市的天气?输入 q 退出查询\n")
  7.     citycode = city.get(cityname)
  8.     if cityname=="q" or cityname=="Q":
  9.         print("退出!")
  10.         exit=True
  11.     else:

  12.         if citycode:
  13.             try:
  14.                 url = ("http://www.weather.com.cn/data/cityinfo/%s.html" % citycode)
  15.                 request = urllib.request.Request(url)
  16.                 response = urllib.request.urlopen(request)
  17.                 content = response.read().decode("utf-8")
  18.                 print('未转化输出:%s'%content)
  19.                 print('url%s'%url)
  20.                 data = json.loads(content)   # 输出转化为字典dict
  21.                 print('转化后输出:%s'%data)
  22.                 print(type(content))
  23.                 print(type(data))
  24.                 result = data['weatherinfo']
  25.                 str_temp = ('%s\n%s ~ %s')%(
  26.                     result['weather'],
  27.                     result['temp1'],
  28.                     result['temp2']
  29.                 )
  30.                 print(str_temp)

  31.             except:
  32.                 print('查询失败')
  33.         else:
  34.             print('没有找到该城市')
复制代码

作者: bobo0769    时间: 2017-11-23 08:26
# -*- coding: utf-8 -*-
from urllib.request import urlopen  #打开网页函数
import urllib
import json
from city import city  #把city文件作为函数引用

f=open('c:\Python34\city.py')
cityname=input('你想查哪个城市的天气?\n')
citycode=city.get(cityname)
if citycode:
    url=("http://www.weather.com.cn/weather1d/%s.shtml#search" %citycode)
    content=urlopen(url).read().decode()  #解码网址
    data=json.loads(content,'utf-8')      #把字符串转成字典
    result=data["weatherinfo"]
    str_temp=("%s\n%s~%s")%(result["weather"],result["temp1"],result["temp2"])
    print(str_temp)
f.close()
不管有没有decode都是在json.loads那里出错,请大神指教
作者: crossin先生    时间: 2017-11-23 22:31
bobo0769 发表于 2017-11-23 08:26
# -*- coding: utf-8 -*-
from urllib.request import urlopen  #打开网页函数
import urllib

那说明你拿到的content不对,你要看看content是什么
作者: wlfrank    时间: 2018-1-2 23:38
各位大佬求帮助,我现在用的新的地址反馈的天气信息但是是乱码,请问这种情况应该怎么处理哪

微信图片_20180102233445.png (42.78 KB, 下载次数: 211)

微信图片_20180102233445.png

1514907325(1).jpg (23.32 KB, 下载次数: 212)

1514907325(1).jpg


作者: wlfrank    时间: 2018-1-2 23:55
wlfrank 发表于 2018-1-2 23:38
各位大佬求帮助,我现在用的新的地址反馈的天气信息但是是乱码,请问这种情况应该怎么处理哪 ...

已核实为网页编码压缩输出问题,已解决http://www.voidcn.com/article/p-qpuzajek-hr.html




欢迎光临 Crossin的编程教室 (https://bbs.crossincode.com/) Powered by Discuz! X2.5