0
votes

I was trying out Twitter API but it give me this error:

Traceback (most recent call last):
File "D:/MAGIC/python/twitterdemo.pu.py", line 23, in
text += status.text.encode('utf-8')
TypeError: Can't convert 'bytes' object to str implicitly

Here is my code:

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')

What am I doing wrong?

1
If you encode it, it has been a str before and is now bytes, but you need a str here. So remove the .encode('utf-b') and try again. - Klaus D.

1 Answers

3
votes

Your text is initialized as a str, and you're trying to add a bytes object (which is what status.text.encode('utf-8') returns) to it. Initialize text as a bytes object and that error should go away:

text = b''

Alternatively, you could skip encoding the text altogether and it should work:

text += status.text