0
votes

I want to download tweets from twitter as data sets for sentiment analysis using Python Twitter API ..

I am using SemEval 2016 task 6 dataset ..So I downloaded "Domain corpus for task B" and I found a Readme file that describe the steps ..

I am just a beginner and I do not know much in python ..I installed python 3.4.3 and I already found easy_install.exe and pip.exe in scripts folder ..

I typed in cmd : "easy_install twitter" as it is written in readme file ...then I tried to apply the steps from Readme file , here are the steps:

The first time you run this, it should open up a web browser, have you log into

Twitter, and show a PIN number for you to enter into a prompt generated by the

script.

  1. Login to Twitter with your user name in your default browser.

  2. Run the script like this to download your credentials: python download_tweets_api.py --dist=Donald_Trump.txt -- output=downloaded_Donald_Trump.txt

  3. Download tweets like so: python download_tweets_api.py --dist=Donald_Trump.txt --output=downloaded_Donald_Trump.txt

I finished step 1 , then I typed in cmd "download_tweets_api.py --dist=Donald_Trump.txt --output=downloaded_Donald_Trump.txt" but I got an error in last line of the file

TypeError: sequence item 1:expected str instance, bytes found

Here is the content of the file "download_tweets_api.py"

import sys
import os
import time
import datetime
import argparse
from twitter import *

parser = argparse.ArgumentParser(description="downloads tweets")
parser.add_argument('--partial', dest='partial', default=None, type=argparse.FileType('r'))
parser.add_argument('--dist', dest='dist', default=None, type=argparse.FileType('r'), required=True)
parser.add_argument('--output', dest='output', default=None,type=argparse.FileType('w'), required=True)
args = parser.parse_args()


CONSUMER_KEY='xxxxxxxxxxx'
CONSUMER_SECRET='xxxxxxxxxxxxxxxxx'

MY_TWITTER_CREDS = os.path.expanduser('~/.my_app_credentials')
if not os.path.exists(MY_TWITTER_CREDS):
oauth_dance("Semeval sentiment analysis", CONSUMER_KEY, CONSUMER_SECRET, MY_TWITTER_CREDS)
oauth_token, oauth_secret = read_token_file(MY_TWITTER_CREDS)
t = Twitter(auth=OAuth(oauth_token, oauth_secret, CONSUMER_KEY, CONSUMER_SECRET))

cache = {}
if args.partial != None:
    for line in args.partial:
        fields = line.strip().split("\t")
        text = fields[-1]
        sid = fields[0]
        cache[sid] = text

for line in args.dist:
    fields = line.strip().split('\t')
    sid = fields[0]

    while not sid in cache:
        try:
            text = t.statuses.show(_id=sid)['text'].replace('\n', '  ').replace('\r', ' ')
            cache[sid] = text.encode('utf-8')
        except TwitterError as e:
            if e.e.code == 429:
                rate = t.application.rate_limit_status()
                reset = rate['resources']['statuses']['/statuses/show/:id'] ['reset']
                now = datetime.datetime.today()
                future = datetime.datetime.fromtimestamp(reset)
                seconds = (future-now).seconds+1
                if seconds < 10000:
                    sys.stderr.write("Rate limit exceeded, sleeping for %s  seconds until %s\n" % (seconds, future))
                    time.sleep(seconds)
            else:
                cache[sid] = 'Not Available'

    text = cache[sid]

    args.output.write("\t".join(fields + [text]) + '\n')

Note you can find the download_tweets_api.py and readme files in the "domain corpus for task B"

1
here is a capture of the error from cmd : mediafire.com/view/0g5k3imjhmcyefc/errpython.JPG - Sarsoura
here is the link to semeval datasets from which I got the link to mentioned corpus alt.qcri.org/semeval2016/task6/index.php?id=data-and-tools - Sarsoura
If you can, you might want to change your CONSUMER_KEY and secret. In the future don't post those values on a public forum. It is like writing your pin code on your bank card! - joel goldstick

1 Answers

0
votes

The issue is with the last line of the download_tweets_api.py script. The script was written in Python 2 and would probably run seamlessly in Python 2. The main reason it is not running in Python 3 is that the last line is trying to join strings with bytes. However, in Python 3, bytes are clearly different from strings, in that you cannot join a byte to a string without coercing one into the other. In the case of this script, either the text variable or the fields variable (or even both) is of bytes elements. So, you may have to modify the variables text and fields before applying the string join function on them.

Basically, you will have to replace the last line of the script with the following:

#Create a function that converts the byte elements of the list fields into strings.
def convert(s):
  try:
    return str(s,encoding='utf8')
  except:
    return s
text = convert(text)
fields = list(map(lambda x: convert(x), fields))
args.output.write("\t".join(fields + [text]) + '\n')

If you do not want to modify the script, then you may have to run it in Python 2, or use the 2to3 module to convert the code to Python 3.

Hope this helps.