我的目标是从 def on_status(self, status):
获取 json 格式的数据。
现在我以类似于 JSON 的方式返回数据,但它不是 JSON:
{'favorited': False, 'contributors': None, 'truncated': False, 'text': 'Lol. As long as you and Tsidi are awake, am not sleeping RT @TboyMP: @Fufu_Tinkies hambo lala wena!! LMAO!!', 'source_url': 'http://ubersocial.com', 'in_reply_to_status_id': None, 'user': <tweepy.models.User object at 0x1b4f3d0>, 'filter_level': 'medium', 'geo': None, 'id': 326808604013379586, 'favorite_count': 0, 'source': 'UberSocial for BlackBerry', 'lang': 'en', 'author': <tweepy.models.User object at 0x1b4f3d0>, 'created_at': datetime.datetime(2013, 4, 23, 21, 23, 37), 'retweeted': False, 'coordinates': None, 'in_reply_to_user_id_str': None, 'entities': {'symbols': [], 'user_mentions': [{'id': 282499717, 'indices': [60, 67], 'id_str': '282499717', 'screen_name': 'TboyMP', 'name': 'Thulane Khanye'}, {'id': 157961325, 'indices': [69, 82], 'id_str': '157961325', 'screen_name': 'Fufu_Tinkies', 'name': 'Nomfundo'}], 'hashtags': [], 'urls': []}, 'in_reply_to_status_id_str': None, 'in_reply_to_screen_name': None, 'id_str': '326808604013379586', 'place': None, 'retweet_count': 0, 'in_reply_to_user_id': None}
正如您所看到的,它使用单引号而不是双引号。我得到这个的方法是:
data = status.__getstate__()
但是我无法使用 json 模块加载
它:它给了我一个错误:
Encountered Exception: expected string or buffer
那么如何从 JSON 中删除数据或将其转换为 JSON?
更新
我想要这样的东西:
>>> data = '[{"fooo":"bar","something":"another bar"}]'
>>> ww = json.loads(data)
>>> ww[0]['fooo']
u'bar'
我希望通过使用 tweepy
数据来完成此操作,从而获得帮助......
谢谢。
最佳答案
这会将来自 def on_status(self, status):
的原始 json 数据写入文件。
此解决方案取自here将原始 json 数据添加到状态对象,以及 here作为使用 tweepy 流功能的骨架代码。
@classmethod
def parse(cls, api, raw):
status = cls.first_parse(api, raw)
setattr(status, 'json', json.dumps(raw))
return status
tweepy.models.Status.first_parse = tweepy.models.Status.parse
tweepy.models.Status.parse = parse
_dir = os.path.dirname(os.path.abspath(__file__))
class CustomStreamListener(tweepy.StreamListener):
def on_status(self, status):
print status.user.screen_name
with codecs.open(os.path.join(_dir, 'tweets.json'), "a", 'utf-8') as textFile:
textFile.write(status.json)
textFile.write('\n')
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
我不是Python专家,但似乎发生的事情是parse方法正在使用新版本进行热修补,然后该新版本被安装到tweepy类层次结构中。新版本调用旧版本,然后在原来的parse方法返回的对象上追加一个json槽。
关于python - StremListener 在 tweepy 中不返回 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16179566/