【问题标题】:Tweepy Tracking Multiple TermsTweepy 跟踪多个术语
【发布时间】:2023-03-19 11:00:01
【问题描述】:

我正在对推文进行内容分析。我正在使用 tweepy 返回与某些术语匹配的推文,然后将 N 条推文写入 CSV 文件进行分析。创建文件和获取数据不是问题,但我想减少数据收集时间。目前我正在遍历文件中的术语列表。一旦达到 N(例如 500 条推文),它就会移动到下一个过滤器项。

我想将我的所有项(少于 400 个)输入到一个变量中,并匹配所有结果。这也有效。我无法得到来自 twitter 的关于状态中匹配的术语的返回值。

class CustomStreamListener(tweepy.StreamListener):
    def __init__(self, output_file, api=None):
        super(CustomStreamListener, self).__init__()
        self.num_tweets = 0
        self.output_file = output_file

    def on_status(self, status):
       cleaned = status.text.replace('\'','').replace('&','').replace('>','').replace(',','').replace("\n",'')
        self.num_tweets = self.num_tweets + 1
        if self.num_tweets < 500:
            self.output_file.write(topicName + ',' + status.user.location.encode("UTF-8") + ',' + cleaned.encode("UTF-8") + "\n")
            print ("capturing tweet number " + str(self.num_tweets) + " for search term: " + topicName)
            return True
        else:
            return False
            sys.exit("terminating")

    def on_error(self, status_code):
        print >> sys.stderr, 'Encountered error with status code:', status_code
        return True # Don't kill the stream

    def on_timeout(self):
        print >> sys.stderr, 'Timeout...'
        return True #Don't kill the stream

with open('termList.txt', 'r') as f:
  topics = [line.strip() for line in f]

for topicName in topics:
    stamp = datetime.datetime.now().strftime(topicName + '-%Y-%m-%d-%H%M%S')
    with open(stamp + '.csv', 'w+') as topicFile:
        sapi = tweepy.streaming.Stream(auth, CustomStreamListener(topicFile))
        sapi.filter(track=[topicName])

特别是我的问题是这个。如果跟踪变量有多个条目,我如何获得匹配的内容?我还要声明我对 python 和 tweepy 比较陌生。

提前感谢您的任何建议和帮助!

【问题讨论】:

    标签: python python-2.7 twitter tweepy


    【解决方案1】:

    您可以对照匹配的字词检查推文文本。比如:

    >>> a = "hello this is a tweet"
    >>> terms = [ "this "]
    >>> matches = []
    >>> for i, term in enumerate( terms ):
    ...     if( term in a ):
    ...             matches.append( i )
    ... 
    >>> matches
    [0]
    >>> 
    

    这将为您提供该特定推文 a 匹配的所有术语。在这种情况下,这只是“这个”术语。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-09
      • 2014-06-20
      • 2015-01-27
      • 2016-04-15
      • 2017-07-28
      • 1970-01-01
      • 2014-11-19
      相关资源
      最近更新 更多