2017-06-05 51 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)])