Разделение и очистка твитов в файле SQLite - PullRequest
0 голосов
/ 02 декабря 2018

Я пытаюсь организовать потоковые твиты в файле SQLite, чтобы результаты выглядели чище.

Однако, я получаю, IndexError: список индекса вне диапазона.Ясно, что я делаю что-то не так с разделением данных, но я просто не знаю, что.

Вот соответствующий код.Если вам нужна дополнительная информация, пожалуйста, прокомментируйте.

class listener(StreamListener):

def on_data(self, data):
    #print(data)

    tweet = data.split(',"text":"')[1].split('","source"')[2].split('","created_at"')[3].split('","geo_coordinates"')[4]
    print(tweet)

    saveThis = str(time.time())+'::'+tweet
    saveFile = open('db.sqlite', 'a')
    saveFile.write(saveThis)
    saveFile.write('\n')
    saveFile.close()
    return True

def on_error(self, status):
    print(status)

ОБНОВЛЕНИЕ:

Это пример твита, созданного без разделения / очистки.

{"created_at":"Sun Dec 02 11:43:26 +0000 2018","id":1069195333006254080,"id_str":"1069195333006254080","text":"AWPS NEWS\nTrump-Xi Meeting Highlights\nand In-Flight Remarks to Press\n -KL Anderson, 12\/2\/2018 **UPDATED\n\nLINK: https:\/\/t.co\/hcIgOFKcdr","source":"\u003ca href=\"http:\/\/twitter.com\/download\/iphone\" rel=\"nofollow\"\u003eTwitter for iPhone\u003c\/a\u003e","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":708701133951377408,"id_str":"708701133951377408","name":"U(X)=0  'A.I~R.I.S'","screen_name":"UofXis0","location":null,"url":null,"description":"Began with an interest in just A.I. (Artificial Intelligence); now expanding into curiosity about R.I.S. (Robotics and Intelligent Systems).","translator_type":"none","protected":false,"verified":false,"followers_count":12,"friends_count":87,"listed_count":3,"favourites_count":0,"statuses_count":588,"created_at":"Sat Mar 12 17:08:12 +0000 2016","utc_offset":null,"time_zone":null,"geo_enabled":false,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"F5F8FA","profile_background_image_url":"","profile_background_image_url_https":"","profile_background_tile":false,"profile_link_color":"1DA1F2","profile_sidebar_border_color":"C0DEED","profile_sidebar_fill_color":"DDEEF6","profile_text_color":"333333","profile_use_background_image":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/708704673746853888\/08z1GxyX_normal.jpg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/708704673746853888\/08z1GxyX_normal.jpg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/708701133951377408\/1457803335","default_profile":true,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"is_quote_status":false,"quote_count":0,"reply_count":0,"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[],"urls":[{"url":"https:\/\/t.co\/hcIgOFKcdr","expanded_url":"https:\/\/www.facebook.com\/1640346062903605\/posts\/2195483604056512\/","display_url":"facebook.com\/16403460629036\u2026","indices":[111,134]}],"user_mentions":[],"symbols":[]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"filter_level":"low","lang":"en","timestamp_ms":"1543751006734"}

Тем не менее, я пытаюсь отобразить только идентификатор твита, текст, созданный_кат, местоположение, географические координаты и подписчиков.

1 Ответ

0 голосов
/ 02 декабря 2018

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

Поскольку это строка, вы можете:

import json
import sqlite3

class listener(StreamListener):
    def on_data(data):
        tweet = json.loads(data)

        # open a database connection to sqlite
        # generally, we would not do this in a function like this
        conn = sqlite3.connect('db.sqlite')
        c = conn.cursor()

        # access each element by its key name
        tweet_values = (time.time(), tweet["ID"], tweet["text"], tweet["created_at"], tweet["location"], tweet["geo_coordinates"], tweet["followers"])
        c.execute('INSERT INTO tweets VALUE (?,?,?,?,?,?,?)', tweet_values)
        c.close()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...