如何实时更改推特流中的过滤词(Python)?

1 投票
2 回答
593 浏览
提问于 2025-04-17 05:46

我需要实时将Twitter Streaming API中的所有推文保存到数据库中,并且要根据某个单词列表进行过滤。为了实现这个目标,我使用了tweetstream,在调用FilterStream()之前,我这样定义了一个单词列表words

words = ["word1","two words","anotherWord"]

我想要的功能是能够在不停止脚本的情况下,随时添加、修改或删除这些单词。为此,我创建了一个纯文本文件,里面包含了我想过滤掉的单词,每个单词之间用换行符分隔。使用这段代码,我可以完美地获取到words列表:

file = open('words.txt','r')
words = file.read().split("\n")

我让这些代码在程序启动时正常工作,但我需要它在每次检查流的时候都能这样做。有什么好主意吗?

2 个回答

0

也许可以这样做:

def rebuild_wordlist(s):
    with open('words.txt','r') as f:
        return set(f.read().split('\n'))

def match(tweet):
    return any(w in tweet for w in words)

words, timestamp = rebuild_wordlist(), time.time()
stream = tweetstream.SampleStream("username", "password")
fstream = ifilter(match, stream)

for tweet in fstream:
    do_some_with_tweet(tweet)
    if time.time() > timestamp + 5.0:
        # refresh the wordlist every 5 seconds
        words, timestamp = rebuild_wordlist(), time.time()

这个 words 集合是一个全局变量,它会在过滤器运行时每隔几秒钟更新一次。

0

你可以在一个线程里读取更新的单词列表,然后在另一个线程里处理推文,两个线程之间可以用Queue来进行沟通。

示例:

读取推文的线程:

def read_tweets(q):
    words = q.get()
    while True:
        with tweetstream.FilterStream(..track=words,..) as stream:
             for tweet in stream: #NOTE:it requires special handling if it blocks
                 process(tweet)
                 try: words = q.get_nowait() # try to read a new word list
                 except Empty: pass
                 else: break # start new connection

读取单词的线程:

def read_words(q):
    words = None
    while True:
        with open('words.txt') as file:
            newwords = file.read().splitlines()
        if words != newwords:
           q.put(newwords)
           words = newwords
        time.sleep(1)

主脚本可能看起来像这样:

 q = Queue(1)
 t = Thread(target=read_tweets, args=(q,))
 t.daemon = True
 t.start()
 read_words(q)

你可以使用inotify或者类似的工具来监控'words.txt'文件的变化,而不是定期去检查。

撰写回答