如何在推文中搜索一个句子

时间:2018-05-13 23:32:54

标签: regex python-3.x sttwitterapi

我正在尝试从Twitter帐户收集数据集,这些帐户以诊断声明的形式发布状态更新,例如“我被诊断为X 今天“,X代表抑郁症。

我能够使用TwitterSearch库,但它只搜索关键字而不是完整的句子。

    from TwitterSearch import *
    try:
        tso = TwitterSearchOrder() # create a TwitterSearchOrder object
        tso.set_keywords(['depression', 'diagnosed']) # let's define all words we would like to have a look for
        tso.set_language('en') # we want to see English tweets only
        tso.set_include_entities(False) # and don't give us all those entity information
    ts = TwitterSearch(
            consumer_key = 'x',
            consumer_secret = 'y',
            access_token = 'z',
            access_token_secret = 't'
 )
    print( tweet['user']['screen_name'], tweet['text'] )

但是我想使用正则表达式来获取与句子匹配的推文。

1 个答案:

答案 0 :(得分:1)

您可以使用set_keywords

搜索完整句子 - 不仅仅是关键字
from TwitterSearch import *
try:
    tso = TwitterSearchOrder() # create a TwitterSearchOrder object
    tso.set_keywords(['I was diagnosed with depression today'])
    tso.set_language('en') # we want to see English tweets only
    tso.set_include_entities(False)

    ts = TwitterSearch(
        consumer_key = 'c',
        consumer_secret = 's',
        access_token = 'at',
        access_token_secret = 'ats'
     )

     # this is where the fun actually starts :)
    for tweet in ts.search_tweets_iterable(tso):
        print( '@%s tweeted: %s' % ( tweet['user']['screen_name'], tweet['text'] ) )

except TwitterSearchException as e: # take care of all those ugly errors if there are some
    print(e)

因此,无需使用正则表达式过滤结果。