Python 代碼中不能出現中文,或者不能輸入中文


最后解決方案。。在文件中添加固定的修改編碼方式。在C:\Python27\Lib\site-packages路徑下新建文件sitecustomize.py

並將如下代碼放進去,重啟idle 即可。

# encoding=gbk
import sys

reload(sys)
sys.setdefaultencoding('gbk')

注意不能將gbk換成utf8或者gb18030.無效

import json
import urllib2
"""import urllib2
web = urllib2.urlopen('http://www.baidu.com')
content = web.read()
fi = open("d:\\c.html",'w')
fi.write(content)
fi.close()

"""
def get(cityname):
    try:
        city={'南京':101190101,'北京':101010100}
        return city[cityname]
    except:
        return 0
     
while 1:
    cityname = raw_input("請輸入要查詢的城市天氣?\n")
    citycode = get(cityname)
    if citycode:
        url = ('http://www.weather.com.cn/data/cityinfo/%s.html'%citycode)
        content = urllib2.urlopen(url).read()
        data = json.loads(content)
        result = data['weatherinfo']
        str_temp = '%s:\n %s\n 最高溫度: %s\n 最低溫度: %s\n'%(  ##就是這里不成出現漢字!!!!
        result['city'],
        result['weather'],
        result['temp1'],
        result['temp2']
        )
        #  str_temp = unicode(str_temp, "gb18030")
##        fi = open("d:\\cc.txt",'w')
##        fi.write(str_temp)
##        fi.close()
        print str_temp
    else:
        print "城市錯誤!"

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM