Использование tweepy и tesseract для извлечения img в твиттере и получения текста - PullRequest
0 голосов
/ 17 марта 2020

Я пытаюсь внедрить ocr в мой твиттер-монитор с помощью tesseract. Мои вопросы: как я могу получить изображения от пользователя и мгновенно запустить OCR. Я наблюдаю за некоторыми твиттер-аккаунтами за последними твитами, если приходит новый и содержит URL-адрес, который я открываю в браузере, теперь я хочу проверить, есть ли внутри твиттер изображение, и распечатать содержимое в консоли. Мой код выглядит так:

import tweepy
import re
import webbrowser
import time
import urllib
from datetime import datetime
# a bunch of access keys
keys = [(example_keys)]

# which key is in use right now
key_index = 0
test = 0
url_store = ''



# Function to extract url from newest tweet 
def get_tweets(username, tweet_mode='extended'):
        # Authorization to consumer key and consumer secret 
        auth = tweepy.OAuthHandler(keys[key_index][0], keys[key_index][1]) 

        # Access to user's access key and access secret 
        auth.set_access_token(keys[key_index][2], keys[key_index][3]) 

        # Calling api 
        api = tweepy.API(auth) 

        # try to get latest tweet until rate limit is reached
        try:
            # Get newest tweet from profile
            tweets = api.user_timeline(screen_name=username, count=1)
            tweet = [tweet.text for tweet in tweets][0]
            print(tweet)



            global url_store
            # regex through tweet for url
            url = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\), ]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', str(tweet))

            # check if url was found and isn't the same as the url from the last tweet
            if (url!=[] and url[0]!=url_store):
                # store url in variable
                url_store=url[0]
                # open the url in webbrowser
                webbrowser.open(url[0])

                # save the html dom to a text file
                urllib.request.urlretrieve(url[0], "test.txt")

        # when rate limit is reached
        except tweepy.TweepError:
            # select the next key from array
            changeKeys() 

        # right now function always returns false
        return False


def changeKeys():
        global key_index
        # increment key_index by 1 unless end of key array is reached -> start from the beginning
        if key_index >= len(keys) - 1:
            key_index = 0
        else:
            key_index += 1

def getIMG():



# Driver code 
if __name__ == '__main__': 
    # boolean if url was found (right now its always false)
    found=False
    # never ending for loop
    while not found:
        # get tweets from specific twitter handle
        found = get_tweets("Trump",)
        time.sleep(0.02)

1 Ответ

0 голосов
/ 18 марта 2020

Это отличный вопрос. Ваш подход к использованию RegEx - неправильный способ поиска изображений.

Каждый твит содержит "Сущности" - см. https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/entities-object

Вы можете использовать их, чтобы получить изображения непосредственно из твитов.

Например:

tweet.entities.urls

Получит все URL-адреса в твите.

...