2017-08-16 119 views
1

当我跑我的Python代码和打印(项目),我收到以下错误:“UCS-2”编解码器不能编码字符位置61-61

UnicodeEncodeError: 'UCS-2' codec can't encode characters in position 61-61: Non-BMP character not supported in Tk 

这里是我的代码:

def getUserFollowers(self, usernameId, maxid = ''): 
    if maxid == '': 
     return self.SendRequest('friendships/'+ str(usernameId) +'/followers/?rank_token='+ self.rank_token,l=2) 
    else: 
     return self.SendRequest('friendships/'+ str(usernameId) +'/followers/?rank_token='+ self.rank_token + '&max_id='+ str(maxid)) 
def getTotalFollowers(self,usernameId): 
    followers = [] 
    next_max_id = '' 
    while 1: 
     self.getUserFollowers(usernameId,next_max_id) 
     temp = self.LastJson 

     for item in temp["users"]: 
      print(item) 
      followers.append(item) 

     if temp["big_list"] == False: 
      return followers    
     next_max_id = temp["next_max_id"] 

我该如何解决这个问题?

+0

错误发生在哪一行,什么是“追随者”,什么是“temp [”users“]? –

+0

追随者是一个列表,并且temp是josn加载的内容self.LastJson = json.loads(response.text)。 –

回答

1

不知道temp["users"]的内容很难猜测,但错误让我们认为它包含非BMP的Unicode Unicode字符,例如emoji

如果你试图在IDLE Python上显示它,你会立即得到那种错误。简单的例子来重现(在IDLE用于Python 3.5):

>>> t = "ab \U0001F600 cd" 
>>> print(t) 
Traceback (most recent call last): 
    File "<pyshell#5>", line 1, in <module> 
    print(t) 
UnicodeEncodeError: 'UCS-2' codec can't encode characters in position 3-3: Non-BMP character not supported in Tk 

\U0001F600表示Unicode字符U + 1F600 笑嘻嘻面

错误的确由Tk的引起了不支持与代码Unicode字符大于FFFF。一个简单的解决方法是过滤出来的字符串:

def BMP(s): 
    return "".join((i if ord(i) < 10000 else '\ufffd' for i in t)) 

'\ufffd'是Unicode的U + FFFD 替换字符

我的例子变成了Python表示:

>>> t = "ab \U0001F600 cd" 
>>> print(BMP(t)) 
ab � cd 

所以您的代码将变为:

for item in temp["users"]: 
     print(BMP(item)) 
     followers.append(item) 
相关问题