Поток api Twitter передает твиты не как объект tweet, а как строку

#python #twitter

#питон #Twitter

Вопрос:

 class TwitterListener(StreamListener):

    def __init__(self):
        pass

    def on_data(self, data):
        print(data.text)
 

Это пример того, что я хочу, чтобы мой слушатель сделал. Я просто хочу напечатать текст переданного твита, но при попытке сделать это я получаю следующую ошибку:

   File "test 2.0.py", line 72, in on_data
    print(data.text)
AttributeError: 'str' object has no attribute 'text'
 

По-видимому, мои твиты передаются как строка, а не как объект tweet. Я все еще могу распечатать все данные, и они выдадут их так, как и должно быть (например, объект), но на самом деле это просто строка, которая выглядит как объект

 {"created_at":"Thu Apr 18 11:44:42  0000 2019","id":1118842788160921600,"id_str":"1118842788160921600","text":"RT @LCARS_24: Donald Trump's great fantasynThat he dreams of anxiously: n"Drain the U.S. Treasury!" nInstead he's facing bankruptcy.nDonaldu2026","source":"u003ca href="http://twitter.com" rel="nofollow"u003eTwitter Web Clientu003c/au003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":1030908792597360640,"id_str":"1030908792597360640","name":"Muffy Bevin","screen_name":"MuffyBevin","location":"Massachusetts, USA","url":null,"description":"I wish we had an American President who loves the USA.  Orange is the new blech!ud83dudc31 #TheResistance. Invoke the 25th for the 45th.ud83cuddfaud83cuddf8","translator_type":"none","protected":false,"verified":false,"followers_count":739,"friends_count":742,"listed_count":0,"favourites_count":24042,"statuses_count":25625,"created_at":"Sat Aug 18 20:06:24  0000 2018","utc_offset":null,"time_zone":null,"geo_enabled":false,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"000000","profile_background_image_url":"http://abs.twimg.com/images/themes/theme1/bg.png","profile_background_image_url_https":"https://abs.twimg.com/images/themes/theme1/bg.png","profile_background_tile":false,"profile_link_color":"981CEB","profile_sidebar_border_color":"000000","profile_sidebar_fill_color":"000000","profile_text_color":"000000","profile_use_background_image":false,"profile_image_url":"http://pbs.twimg.com/profile_images/1030913540708814849/QVRTrBUj_normal.jpg","profile_image_url_https":"https://pbs.twimg.com/profile_images/1030913540708814849/QVRTrBUj_normal.jpg","profile_banner_url":"https://pbs.twimg.com/profile_banners/1030908792597360640/1538050843","default_profile":false,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"retweeted_status":{"created_at":"Thu Apr 18 11:31:27  0000 2019","id":1118839453798129665,"id_str":"1118839453798129665","text":"Donald Trump's great fantasynThat he dreams of anxiously: n"Drain the U.S. Treasury!" nInstead he's facing bankruptu2026 https://t.co/l2O1k49QUZ","source":"u003ca href="http://twitter.com" rel="nofollow"u003eTwitter Web Clientu003c/au003e","truncated":true,"in_reply_to_status_id":1118837452196573184,"in_reply_to_status_id_str":"1118837452196573184","in_reply_to_user_id":829977013888782338,"in_reply_to_user_id_str":"829977013888782338","in_reply_to_screen_name":"LCARS_24","user":{"id":829977013888782338,"id_str":"829977013888782338","name":"Bill Morris  ud83cudf0e","screen_name":"LCARS_24","location":null,"url":null,"description":"#TheResistance #resist #FBR #GetMoneyOut #GreenNewDeal #MedicareForAll #unhackthevote #LockTrumpUp #ImpeachTrump #impeach45 #VoteBlue #BlueWave2020","translator_type":"none","protected":false,"verified":false,"followers_count":42828,"friends_count":47034,"listed_count":61,"favourites_count":28680,"statuses_count":65692,"created_at":"Fri Feb 10 08:55:15  0000 2017","utc_offset":null,"time_zone":null,"geo_enabled":false,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"000000","profile_background_image_url":"http://abs.twimg.com/images/themes/theme1/bg.png","profile_background_image_url_https":"https://abs.twimg.com/images/themes/theme1/bg.png","profile_background_tile":false,"profile_link_color":"000000","profile_sidebar_border_color":"000000","profile_sidebar_fill_color":"000000","profile_text_color":"000000","profile_use_background_image":false,"profile_image_url":"http://pbs.twimg.com/profile_images/833910755560808448/kv8iyfQh_normal.jpg","profile_image_url_https":"https://pbs.twimg.com/profile_images/833910755560808448/kv8iyfQh_normal.jpg","profile_banner_url":"https://pbs.twimg.com/profile_banners/829977013888782338/1512210973","default_profile":false,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"is_quote_status":false,"extended_tweet":{"full_text":"Donald Trump's great fantasynThat he dreams of anxiously: n"Drain the U.S. Treasury!" nInstead he's facing bankruptcy.nDonald Trump promotes division,nFills the air with hateful friction.nTo be President for Life's his life's ambition.nInstead let's make it "life in prison."","display_text_range":[0,275],"entities":{"hashtags":[],"urls":[],"user_mentions":[],"symbols":[]}},"quote_count":0,"reply_count":0,"retweet_count":7,"favorite_count":11,"entities":{"hashtags":[],"urls":[{"url":"https://t.co/l2O1k49QUZ","expanded_url":"https://twitter.com/i/web/status/1118839453798129665","display_url":"twitter.com/i/web/status/1u2026","indices":[117,140]}],"user_mentions":[],"symbols":[]},"favorited":false,"retweeted":false,"filter_level":"low","lang":"en"},"is_quote_status":false,"quote_count":0,"reply_count":0,"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[],"urls":[],"user_mentions":[{"screen_name":"LCARS_24","name":"Bill Morris  ud83cudf0e","id":829977013888782338,"id_str":"829977013888782338","indices":[3,12]}],"symbols":[]},"favorited":false,"retweeted":false,"filter_level":"low","lang":"en","timestamp_ms":"1555587882448"} 

Ответ №1:

Это похоже на объект json, поэтому попробуйте:

 import json

class TwitterListener(StreamListener):

    def __init__(self):
        pass

    def on_data(self, data):
        deserialized = json.loads(data)
        print(deserialized['text'])
 

Комментарии:

1. Спасибо, теперь работает 😉 Только что начал несколько дней назад с python, поэтому довольно новичок во всем этом: D