2017-08-16 113 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) 
相關問題