编程语言
首页 > 编程语言> > python-Tweepy跟踪多个术语

python-Tweepy跟踪多个术语

作者:互联网

我正在对推文进行内容分析.我正在使用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])

具体来说,我的问题是这个.如果track变量有多个条目,如何获得匹配的内容?我还要指出,我是python和tweepy的新手.

在此先感谢您的任何建议和帮助!

解决方法:

您可以根据匹配条件检查推文文本.就像是:

>>> 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相匹配的所有术语.在这种情况下,这仅仅是“ this”一词.

标签:python,python-2-7,twitter,tweepy
来源: https://codeday.me/bug/20191012/1902734.html