Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何通过语言标签和使用Tweepy的计数过滤器来传输推文?_Python_Pandas_Numpy_Twitter_Tweepy - Fatal编程技术网

Python 如何通过语言标签和使用Tweepy的计数过滤器来传输推文?

Python 如何通过语言标签和使用Tweepy的计数过滤器来传输推文?,python,pandas,numpy,twitter,tweepy,Python,Pandas,Numpy,Twitter,Tweepy,所以我想做的是Twitters API的实时推文:只针对“英国退出”标签,只针对英语,以及特定数量的推文(1k-2k) 到目前为止,我的代码将实时流化推特,但无论我以何种方式修改它,我要么最终导致它忽略计数并无限期地流化,要么我会出错。如果我将其更改为仅流式传输特定用户的Tweets,则count函数可以工作,但它会忽略hashtag。如果我为给定的hashtag流式传输所有内容,它将完全忽略计数。我曾经尝试过修复它,但我经验不足,而且真的遇到了麻烦 如果我能在如何同时勾选所有这些方框方面得到一

所以我想做的是Twitters API的实时推文:只针对“英国退出”标签,只针对英语,以及特定数量的推文(1k-2k)

到目前为止,我的代码将实时流化推特,但无论我以何种方式修改它,我要么最终导致它忽略计数并无限期地流化,要么我会出错。如果我将其更改为仅流式传输特定用户的Tweets,则count函数可以工作,但它会忽略hashtag。如果我为给定的hashtag流式传输所有内容,它将完全忽略计数。我曾经尝试过修复它,但我经验不足,而且真的遇到了麻烦

如果我能在如何同时勾选所有这些方框方面得到一些帮助,我将不胜感激! 到目前为止,下面的代码只会无限期地传输“英国退出”推文,因此忽略计数=10

由于我在玩,代码底部有点乱,抱歉:

import numpy as np
import pandas as pd
import tweepy
from tweepy import API
from tweepy import Cursor
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import Twitter_Credentials
import matplotlib.pyplot as plt

# Twitter client - hash out to stream all


class TwitterClient:
    def __init__(self, twitter_user=None):
        self.auth = TwitterAuthenticator().authenticate_twitter_app()
        self.twitter_client = API(self.auth)

        self.twitter_user = twitter_user

    def get_twitter_client_api(self):
        return self.twitter_client

# Twitter authenticator


class TwitterAuthenticator:
    def authenticate_twitter_app(self):
        auth = OAuthHandler(Twitter_Credentials.consumer_key, Twitter_Credentials.consumer_secret)
        auth.set_access_token(Twitter_Credentials.access_token, Twitter_Credentials.access_secret)
        return auth

class TwitterStreamer():
    # Class for streaming and processing live Tweets
    def __init__(self):
        self.twitter_authenticator = TwitterAuthenticator()

    def stream_tweets(self, fetched_tweets_filename, hash_tag_list):

        # this handles Twitter authentication and connection to Twitter API
        listener = TwitterListener(fetched_tweets_filename)
        auth = self.twitter_authenticator.authenticate_twitter_app()
        stream = Stream(auth, listener)
        # This line filters Twitter stream to capture data by keywords
        stream.filter(track=hash_tag_list)

# Twitter stream listener

class TwitterListener(StreamListener):
    # This is a listener class that prints incoming Tweets to stdout
    def __init__(self, fetched_tweets_filename):
        self.fetched_tweets_filename = fetched_tweets_filename

    def on_data(self, data):
        try:
            print(data)
            with open(self.fetched_tweets_filename, 'a') as tf:
                tf.write(data)
            return True
        except BaseException as e:
            print("Error on_data: %s" % str(e))
        return True

    def on_error(self, status):
        if status == 420:
            # Return false on data in case rate limit occurs
            return False
        print(status)

class TweetAnalyzer():
    # Functionality for analysing and categorising content from tweets

    def tweets_to_data_frame(self, tweets):
        df = pd.DataFrame(data=[tweet.text for tweet in tweets], columns=['tweets'])

        df['id'] = np.array([tweet.id for tweet in tweets])
        df['len'] = np.array([len(tweet.text) for tweet in tweets])
        df['date'] = np.array([tweet.created_at for tweet in tweets])
        df['source'] = np.array([tweet.source for tweet in tweets])
        df['likes'] = np.array([tweet.favorite_count for tweet in tweets])
        df['retweets'] = np.array([tweet.retweet_count for tweet in tweets])

        return df


if __name__ == "__main__":

    auth = OAuthHandler(Twitter_Credentials.consumer_key, Twitter_Credentials.consumer_secret)
    auth.set_access_token(Twitter_Credentials.access_token, Twitter_Credentials.access_secret)
    api = tweepy.API(auth)

    for tweet in Cursor(api.search, q="#brexit", count=10,
                               lang="en",
                               since="2019-04-03").items():
        fetched_tweets_filename = "tweets.json"
        twitter_streamer = TwitterStreamer()
        hash_tag_list = ["Brexit"]
        twitter_streamer.stream_tweets(fetched_tweets_filename, hash_tag_list)

您尝试使用两种不同的方法访问Twitter API—流媒体是实时的,搜索是一次性的API调用

由于流媒体是连续和实时的,因此无法对其应用结果计数-代码只会打开一个连接,说“嘿,从现在开始向我发送所有包含
hash\u tag\u list
”的推文,然后坐在那里听。此时,您将进入
StreamListener
,对于收到的每条Tweet,您将它们写入一个文件

您可以在此处应用计数器,但需要将其包装在\u data处理程序上的
StreamListener
中,并为接收到的每个Tweet递增计数器。当你收到1000条推文时,停止收听

对于搜索选项,您有几个问题。。。第一个问题是,自2019年以来,您一直在请求tweet,但标准搜索API只能追溯到7天以前。很明显,你只要求发10条推特。不过,按照您编写方法的方式,实际发生的是,对于API返回的10条Tweet集合中的每条Tweet,您随后创建一个实时流连接,并开始侦听和写入文件。所以这是行不通的


您需要选择一个-搜索1000条Tweet并将其写入文件(切勿设置
TwitterStreamer()
),或者,收听1000条Tweet并将其写入文件(将Tweet的
放入光标(api.search…
并直接跳到拖缆).

只需将标签符号添加到列表中的搜索短语,它将匹配使用特定标签的推文。它区分大小写,因此您可能希望在搜索数组中添加尽可能多的选项。仅使用“Brexit”匹配可能使用或可能不使用标签但包含关键字“Brexit”的推文


hash_tag_list=[“#英国脱欧”]

您可能需要添加解释。哦,嗯,好的..可以