Tweepy - 计算一个单词出现的次数

时间:2021-02-09 21:17:23

标签: python python-3.x

因此使用 Tweepy 流式传输“Python”这个词,我想获取每条推文,看看列表中是否存在任何词。如果是,我想打印“word1: 1”。如果该词在该推文中出现两次,或者在另一条推文中再次出现以打印“word1: 2”,我希望它能够处理一个词列表,而不仅仅是一个搜索词。

这是我目前所拥有的:

    import json
    import tweepy
    
    from collections import Counter
    
    class MyStreamListener(tweepy.StreamListener):
        def __init__(self, api):
            self.api = api
            self.me = api.me()
    
        def on_status(self, tweet):
            print(f"{tweet.user.name}:{tweet.text}")
    
    
            words = {"Python", "python", "code", "snake", "Snake"}    # words to keep counts for
            word_counts = Counter()
            tweet = tweet.text
            lines = tweet.split()
    
    
    
            print(lines)
            
            for line in tweet:
                tracked_words = [w for word in line.split() if (w:=word.lower()) in words]
                word_counts.update(tracked_words)
                print(*[f'{word}: {word_counts[word]}'
                        for word in set(tracked_words)], sep=', ')
    
    
    
        def on_error(self, status):
            print("Error detected")
    
    # Authenticate to Twitter
    auth = tweepy.OAuthHandler("ABC123ABC123ABC123ABC123")
    auth.set_access_token("ABC123ABC123ABC123ABC123")
    
    # Create API object
    api = tweepy.API(auth, wait_on_rate_limit=True,
        wait_on_rate_limit_notify=True)
    
    tweets_listener = MyStreamListener(api)
    stream = tweepy.Stream(api.auth, tweets_listener)
    stream.filter(track=["Python"], languages=["en"])

我想在当前打印中添加它会打印一堆空行,然后打印推文,然后是拆分推文。它从不打印 word : #

0 个答案:

没有答案