解决python2.7常见的中文乱码问题
解决中文乱码的三个问题
1、代码里有中文内容,控制台报“SyntaxError: Non-ASCII character '\xe8' in file D:/workplace/batchGetData/venv/com/get_org_id.py on line 42, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details”
解决:*.py文件第一行添加下面代码可以解决问题
# -*- coding: UTF-8 -*-
2、列表里的内容控制台打印出来是[u'\u6d4b\u8bd5\u521b\u5efa\u5b66\u6821', u'490079345147', 0]
解决:*.py文件里把list转成json,可以正常输出中文:json.dumps(list, encoding="UTF-8", ensure_ascii=False)
[ "测试创建学校", "490079345147", 0]
3、导出文件的时候,提示Traceback (most recent call last): File "D:/workplace/batchGetData/venv/com/get_org_id.py", line 48, in <module> json.dump(param, f, encoding="utf-8", ensure_ascii=False) File "D:\Python27\lib\json\__init__.py", line 190, in dump fp.write(chunk) UnicodeEncodeError: 'ascii' codec can't encode characters in position 4-13: ordinal not in range(128)
解决:文件流要先改成json,然后把json写入文件时,也要进行编码,下面两步的内容缺一不可
param = json.dumps(project, encoding="UTF-8", ensure_ascii=False)
json.dump(project, f, encoding="utf-8", ensure_ascii=False)
导出发现还是乱码问题
导出还是乱码.png
解决:加入下面这段代码,可以解决导出不是中文的问题
import sys
reload(sys)
sys.setdefaultencoding('utf8')
# -*- coding: UTF-8 -*-
import json
import requests
import sys
reload(sys)
sys.setdefaultencoding('utf8')
url = "http://XXX/v1.0/schools/withServices?$count=true&$limit=10"
payload = "{}"
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer "F4138BF83405E3B1B01A521337415C97A0DFDE23B417615AC35A650E0DAEFCED66CC11D183F04A25DE25ED31AD03BEAA055DE11107DFA4EC-00000000"',
'sdp-app-id': '144fa1cf-b8c7-43b2-b88f-a37005e6f6c7',
'userId': '2138822989'
}
response = requests.request("GET", url, headers=headers, data = payload)
print(response.text.encode('utf8'))
project = []
res = json.loads(response.text)
for d in res["items"]:
project.append(d["name"])
project.append(d["org_id"])
org_id = d["org_id"]
url = "http://XXX/v1.0/opening_services/old/application_package/queryOpenStatus?org_id="+ str(org_id)
payload = "{}"
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer "F4138BF83405E3B1B01A521337415C97A0DFDE23B417615AC35A650E0DAEFCED66CC11D183F04A25DE25ED31AD03BEAA055DE11107DFA4EC-00000000"',
'sdp-app-id': '144fa1cf-b8c7-43b2-b88f-a37005e6f6c7',
'userId': '2138822989'
}
response1 = requests.request("GET", url, headers=headers, data=payload)
# print(response1.text.encode('utf8'))
res1 = json.loads(response1.text)
project.append(res1['opened_num'])
#解决乱码问题
print json.dumps(project, encoding="UTF-8", ensure_ascii=False)
param = json.dumps(project, encoding="UTF-8", ensure_ascii=False)
#方法一:
#f=open(r"xxx")这样可以在没有文件名的情况下新建文件
f = open(r"D:\workplace\batchGetData\response.csv", "w+")
json.dump(param, f, encoding="utf-8", ensure_ascii=False)
#方法二:
#导出文件类型可以随意改成*.json、*.csv、*.txt
# with open(r"D:\workplace\batchGetData\response.csv", "w+") as f:
# json.dump(param, f, encoding="utf-8", ensure_ascii=False)
f.close()
print("文件创建成功")