Есть ли способ получить из твита слова, которые не используются для фильтрации твитов? - PullRequest
0 голосов
/ 01 августа 2020

Я транслирую твиты с помощью Tweepy, отфильтрованных по этим тегам ["corona", "quarantine", "covid19"]

Например, если у меня есть этот твит: «Я упал с лестницы и съел яблоко so no doctor #quarantine "Я хотел бы получить такие строки, как" лестница "," яблоко "и" доктор "в виде набора ключевых слов

Есть ли способ сделать это?

Я новичок в python и использую видеоуроки на Youtube, чтобы начать этот проект

class StdOutListener(StreamListener):

    def on_data(self, data):
        print data
        return True

    def on_error(self, status):
        print status

if __name__ == '__main__':
    
    lis = StdOutListener()
    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    stream = Stream(auth, lis)

    stream.filter(track=['covid19','corona','quarantine'])

Ответы [ 2 ]

1 голос
/ 01 августа 2020

Вы можете использовать понимание списка:

tags =  ["corona", "quarantine", "covid19"]
tweet = "I fell down the stairs and ate an apple so no doctor #quarantine"

# print each word in the tweet that is longer than two characters and
# does not contain any of the tag words
print([word for word in tweet.split() if len(word) > 2 and not any(tag in word for tag in tags)])

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

0 голосов
/ 01 августа 2020

Как насчет этого? -

Если вы хотите разбить твит на слова, тогда -

s =  'fell down the stairs and ate an apple so no doctor #quarantine'
allwords = s.split(' ')
allwords

#output
['fell', 'down', 'the', 'stairs', 'and', 'ate', 'an', 'apple', 'so', 'no', 'doctor','#quarantine']

Затем вы можете разделить слова тегом #, сделав это -

hastags = [i for i in allwords if i[:1]=='#']
hastags

#output
['#quarantine']

Далее вы можете отфильтровать наши слова с тегами #, сделав это -

otherwords = [i for i in allwords if i not in hastags]
otherwords

#output
['fell', 'down', 'the', 'stairs', 'and', 'ate', 'an', 'apple', 'so', 'no', 'doctor']

Для больших наборов данных и длинного списка определенных c хэштегов я бы рекомендовал сделать это -

tags = ["corona", "quarantine", "covid19"]
[i for i in s.split(' ') if i.strip('#') not in tags]

#output
['fell', 'down', 'the', 'stairs', 'and', 'ate', 'an', 'apple', 'so', 'no', 'doctor']

Если у вас есть ситуация, когда теги, используемые для фильтрации твитов, могут НЕ иметь # перед ними, но вы все равно хотите их отфильтровать, тогда -

tags = ["corona", "quarantine", "covid19"]
print([i for i in s.split(' ') if i.strip('#') not in tags and i not in tags])

#output
['fell', 'down', 'the', 'stairs', 'and', 'ate', 'an', 'apple', 'so', 'no', 'doctor']
...