我正在用tweepy来处理推文:
class StdOutListener(StreamListener):
def on_data(self, data):
process(json.loads(data))
return True
l = StdOutListener()
stream = Stream(auth, l)
stream.filter(track=utf_words)process函数获取包含在tweet中的URL内容(包含请求),使用nltk处理数据(我猜这需要一些CPU),并将结果保存到Mongo中。
问题是获取包含URL的内容需要很长时间,因此限制了我的处理速度。我怎样才能加速这件事?
发布于 2013-09-16 03:34:24
您可以使用python的threading模块:
import threading
class YourThreadSubclass(threading.Thread):
def __init__(self,your_args):
threading.Thread.__init__(self)
#do whatever setup you want
def run(self):
process_data(self.some_property)
threads = [YourThreadSubclass(args) for args in Iterable]
for t in threads:
t.start()
for t in threads:
t.join()
return reduce(combiner, (t.result_field for t in threads))更多信息在这里:http://docs.python.org/2/library/threading.html
编辑:更直接地说,每当调用on_data时,您都可以分出一个线程。
def on_data(self, data):
YourThreadSubclass(data).start()分叉线程将异步存储其结果。
如果您正在处理大量请求,您可能还需要使用线程池来管理您的线程。Docs 这里
https://stackoverflow.com/questions/18818967
复制相似问题