2017-08-01 77 views
1

我已经看到很多话题打开这个问题,但他们都没有帮助我解决这个问题。我有一个包含许多不同字符的文本的数据集。因此,我在使用Python 2.7.13上的Requests库进行POST请求之前对文本进行了编码。请求发布UnicodeEncodeError出现,尽管utf-8编码

我的代码如下:

# -*- coding: utf-8 -*- 
# encoding=utf8 
import sys 
reload(sys) 
sys.setdefaultencoding('utf8') 
import json 
import requests 
text = """So happy to be together on your birthday! ❤ Thankful for real life. ❤ A post shared by Jessica Chastain (@jessicachastain) on Nov 13, 2016 at 5:22am PST""" 
textX = json.dumps({'text': text.encode('utf-8')}) 
r = requests.post('http://####', data=textX, 
         headers={'Content-Type': 'application/json; charset=UTF-8'}) 
print(r.text) 

数据以JSON格式发送。无论我尝试将文本编码为UTF-8,我仍然从请求中收到以下错误。

UnicodeEncodeError: 'latin-1' codec can't encode character '\u2764' in 
position 42: Body ('❤') is not valid Latin-1. Use body.encode('utf-8') 
if you want to send it encoded in UTF-8. 

编辑: 语法错误固定的,但问题

+0

是不是你缺少一个右')''中= textX json.dumps({”文本':text.encode('utf-8'})'?应该是造成语法错误... 你可以发布其余的回溯:哪一行产生UnicodeError? – cowbert

+0

@cowbert,你是对的,但出现语法错误,但即使语法正确,我也得到了Unicode错误。 – Furkanicus

回答

0

的不是事业,为json.dumps默认为生成唯一的ASCII字符串,从而消除编码问题。该错误不使用Unicode字符串。确保保存宣布编码源文件(#coding=utf8):

# coding=utf8 
import json 
text = u"""So happy to be together on your birthday! ❤ Thankful for real life. ❤ A post shared by Jessica Chastain (@jessicachastain) on Nov 13, 2016 at 5:22am PST""" 
textX = json.dumps({u'text': text}) 

输出:

'{"text": "So happy to be together on your birthday! \\u2764 Thankful for real life. \\u2764 A post shared by Jessica Chastain (@jessicachastain) on Nov 13, 2016 at 5:22am PST"}' 
+0

感谢@ mark-tolonen从您的答案中获得了答案。与您的输出相同,当我尝试发布文本时,仍然出现以下错误X UnicodeEncodeError:'latin-1'编解码器无法编码 中的字符'\ u2764'位置42:正文('❤')无效Latin-1的。如果您想以UTF-8编码发送它,请使用body.encode('utf-8') 。 – Furkanicus

+1

@Furkanicus其实我的格式在输出上不正确,这抑制了实际的内容。现在已经修复了。没有'\ u2764'字符,而是一个字面转义代码''\\ u2764',所以不会有Unicode字符。所以这看起来像是其他地方的错误。你没有在任何地方指定'latin-1'。 JSON可以使用转义码进行传输,当服务器处理连接时,它仍然会在连接的另一端进行解码。 –