2017-06-05 30 views
1

我的代碼定義了一個穩定的形式輸出鳴叫工程由TweepyPython的獲得實時的鳴叫。我只想得到鳴叫的創建日期和內容,所以我定義如下如何通過蟒蛇得到實時的鳴叫

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 

但是輸出並不完全顯示「Created_at:.....,Text .....」。它在創建日期更改時更改。

{'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'} 

那麼如何才能解決這個整天的所有微博顯示在1種形式「Created_at:.....,文字​​.....」。
我很初學者,所以我需要你的幫助。

非常感謝。

回答

1

您使用的是dict(字典)類型來存儲的tweet(tweet_data)。 Python的字典不維護存儲的字段的順序。因此,你看到某些情況下與{'Text': ..., 'Created_at': ...}而另{'Created_at': ..., 'Text': ...}

如果你想保持字段的順序,你可以使用OrderedDict類型:

tweet_data = OrderedDict([('Created_at', tweet_created_date), ('Text', tweet_text)])