TypeError:无法转换'字节'在python中隐式地反对str?

时间:2016-12-07 12:32:42

标签: python python-3.x twitter

我正在试用Twitter API,但它给了我这个错误:

  

追踪(最近的呼叫最后):
  文件" D:/MAGIC/python/twitterdemo.pu.py" ;,第23行,中
     text + = status.text.encode(' utf-8')
  TypeError:无法转换'字节'隐含地反对str

这是我的代码:

import sys
import operator
import requests
import json
import twitter
from watson_developer_cloud import PersonalityInsightsV2 as PersonalityInsights

twitter_consumer_key = ''  
twitter_consumer_secret = ''  
twitter_access_token = ''  
twitter_access_secret = ''

twitter_api = twitter.Api(consumer_key=twitter_consumer_key, consumer_secret=twitter_consumer_secret, access_token_key=twitter_access_token, access_token_secret=twitter_access_secret)

handle = "@somethingsoemthing"
statuses = twitter_api.GetUserTimeline(screen_name=handle, count=200, include_rts=False)

text = ""

for status in statuses:
  print (status.text)
  if(status.lang == 'en'): #Enligh tweets
    text += status.text.encode('utf-8')

我做错了什么?

1 个答案:

答案 0 :(得分:3)

您的text初始化为str,并且您正在尝试添加bytes对象(status.text.encode('utf-8')返回的对象)。将text初始化为bytes对象,该错误应该消失:

text = b''

或者,您可以完全跳过对文本的编码,它应该可以工作:

text += status.text