1

My code works for getting real time tweets by Tweepy package of Python. I only want to get the created date and content of tweet so I define like below

 def on_status(self, status):
    tweet_text = status.text
    tweet_created_date = str(status.created_at)
    tweet_data = {'Created_at':tweet_created_date,'Text':tweet_text}
    self.num_tweets += 1
    if self.num_tweets < 10001:
        with open('data.txt','a') as tf:
            #tf.write(tweet_data + '\n')
            tf.write(format(tweet_data) + '\n')
        return True
    else:
        return False

But the outputs don't show exactly "Created_at:....., Text.....". It changes when the created date changes.

{'Text': 'RT @owen_author: Tiger Lily of Bangkok: a serial killer is on the loose in #BKK NaNoWriMo winner #Bangkoknoir #thri…', 'Created_at': '2017-06-01 22:18:28'}
{'Text': 'RT @MidwestBG: #NP Silent Stranger @SilentStranger6 - Bangkok by Night (Alternate Mix) on @MidwestBG', 'Created_at': '2017-06-01 22:18:38'}
{'Text': 'RT @IronWavesRadio: #NP Silent Stranger @SilentStranger6 - Bangkok by Night (Alternate Mix) on @IronWavesRadio', 'Created_at': '2017-06-01 22:18:42'}
{'Created_at': '2017-06-02 02:34:31', 'Text': '"RT @EXOXIUMINMAMA: 17.06.10\n2017 BANGKOK SUPER LIVE  \n#2017bkksuperlive \n\n#XIU의미소가우리에겐최고! \nXIUMIN's Smile is the BEST! \n\nรายละเอียด\n… "'}
{'Created_at': '2017-06-02 02:34:39', 'Text': '(w1-59)Stamps,Thailand stamps,MNH,wild animals,art,minerals #thailand #bangkok'}
{'Created_at': '2017-06-02 02:34:42', 'Text': 'RT @joeybirlem: reacting to cringey musicallys youtube video out tomorrow! bangkok vlog out on friday be readyyyyyyy'}

So how can I fix this for all tweets of all day is shown in 1 form "Created_at:....., Text.....".
I'm very beginner so I need your help.

Thank you very much.

1 Answers1

1

You are using a dict (dictionary) type to store the tweets (tweet_data). Python's dictionaries do not maintain the order of the stored fields. Thus, you see some instances with {'Text': ..., 'Created_at': ...} while others with {'Created_at': ..., 'Text': ...}.

If you want to maintain the order of the fields, you can use OrderedDict type:

tweet_data = OrderedDict([('Created_at', tweet_created_date), ('Text', tweet_text)])
Shai
  • 111,146
  • 38
  • 238
  • 371