[新人求助]python3.5引用字典出错
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了[新人求助]python3.5引用字典出错,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2961字,纯文字阅读大概需要5分钟。
内容图文
1.我在一份city.py 文件中收录了城市名字对应的城市编号,并用这个编号去中国天气网查询数据部分数据格式是这样的:
city = {
'北京': '101010100',
'海淀': '101010200',
'朝阳': '101010300',
'顺义': '101010400',
'怀柔': '101010500',
'通州': '101010600',
'昌平': '101010700',
'延庆': '101010800',
'丰台': '101010900',
'石景山': '101011000',
'大兴': '101011100',
'房山': '101011200',
'密云': '101011300',
'门头沟': '101011400',
'平谷': '101011500',
下面是我的代码
# -*- coding:utf-8 -*-
import urllib3
import json
from city import city
cityname = input('您想查询哪个城市的天气?\n')
citycode = city.get(cityname)
if citycode:
url = ('http://www.weather.com.cn/data/cityinfo/%s.html'%citycode)
content = urllib3.urlopen(url).read()
print(content)
运行报错 说:
D:\learnpy\weather
python weather.py
杭州
Traceback (most recent call last):
File "weather.py", line 7, in
cityname = input()
EOFError
究竟哪一步出了问题呢?
回复内容:
1.我在一份city.py 文件中收录了城市名字对应的城市编号,并用这个编号去中国天气网查询数据
部分数据格式是这样的:
city = {
'北京': '101010100',
'海淀': '101010200',
'朝阳': '101010300',
'顺义': '101010400',
'怀柔': '101010500',
'通州': '101010600',
'昌平': '101010700',
'延庆': '101010800',
'丰台': '101010900',
'石景山': '101011000',
'大兴': '101011100',
'房山': '101011200',
'密云': '101011300',
'门头沟': '101011400',
'平谷': '101011500',
下面是我的代码
# -*- coding:utf-8 -*-
import urllib3
import json
from city import city
cityname = input('您想查询哪个城市的天气?\n')
citycode = city.get(cityname)
if citycode:
url = ('http://www.weather.com.cn/data/cityinfo/%s.html'%citycode)
content = urllib3.urlopen(url).read()
print(content)
运行报错 说:
D:\learnpy\weather
python weather.py
杭州
Traceback (most recent call last):
File "weather.py", line 7, in
cityname = input()
EOFError
究竟哪一步出了问题呢?
EOFError
的错误是因为遇到了不期望的结尾, 这算是一个sublime
的 bug, 想解决可以看这里
Running Python interactively from within Sublime Text 2
另外建议你用requests
, urllibx
系列太坑爹, 改了下你的代码, 基本可用
import json
import requests
from city import city
cityname = input('您想查询哪个城市的天气?\n')
citycode = city[cityname]
if citycode:
url = ('http://www.weather.com.cn/data/cityinfo/%s.html' % citycode)
content = requests.get(url)
string = content.text.encode(content.encoding).decode("utf-8")
print(json.dumps(json.loads(string), ensure_ascii=False, indent=4))
输出
您想查询哪个城市的天气?
北京
{
"weatherinfo": {
"ptime": "18:00",
"weather": "晴",
"cityid": "101010100",
"temp2": "16℃",
"temp1": "-2℃",
"city": "北京",
"img2": "d0.gif",
"img1": "n0.gif"
}
}
你用的是不是sunlime text编辑代码的?可以把你的代码用IDLE或者pycharm之类的试试,看看能不能执行出结果。
尝试一下把input函数换成sys.stdin.readline()
import sys
city = sys.stdin.readline()[:-1:] # readline函数的返回值会包括换行符
内容总结
以上是互联网集市为您收集整理的[新人求助]python3.5引用字典出错全部内容,希望文章能够帮你解决[新人求助]python3.5引用字典出错所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。