使用 json 加载和阅读 Twitter 状态

Loading and reading Twitter status with json

您好,我正在修改 Python (2.7) 中的一些代码,我写信是为了与 Twitter 的更新 API 一起工作,想知道是否有人可以解决这个相当简单的问题...

我正在阅读帐户的 最新 提及作为变量 'mention' 和字符串本身(请参阅下面的代码了解我如何从 api):

Status(contributors=None, truncated=False, text=u'Here we have a tweet', is_quote_status=False, retweeted=True, u'created_at': u'Sun Dec 25 22:26:12 +0000 2011')

(每次返回的提及中显然都有更多内容,很多行,但我已将其精简到希望所有必要的部分)

我想把它放到一个函数中并用json.loads加载它以便使用它(这就是问题所在)...我的代码如下:

import ConfigParser
import json
import re
import csv
from tweepy import OAuthHandler
from tweepy import API
from datetime import datetime, time, timedelta
import traceback


consumer_key = ''
consumer_secret = ''
access_token = ''
access_token_secret = ''
account_screen_name = ''
account_user_id = ''

auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = API(auth)

mentions = api.mentions_timeline(count=1)
now = datetime.now()

def myfunction(mention):
        tweet = json.loads(mention.strip())    
        retweeted = tweet.get('retweeted')
        from_self = tweet.get('user',{}).get('id_str','') == account_user_id

        if retweeted is not None and not retweeted and not from_self:
            try:
                DO SOME THINGS

        else:
            DON'T DO THINGS

for mention in mentions:
    print mention.text
    if now < (mention.created_at + timedelta(hours=1) + timedelta(seconds=10)):
        print "Mention was in the last ten seconds"
        myfunction(mention)
    else:
        print "Wasn't in last ten seconds, so do nothing."

但是,如果我这样做,则会收到错误消息:

Traceback (most recent call last):
  File "stuff.py", line 100, in <module>
    myfunction(mention)
  File "stuff.py", line 40, in replier
    tweet = json.loads(mention.strip())
AttributeError: 'Status' object has no attribute 'strip'

在 json 方面我不是最好的,所以这可能是一个明显的问题,但有人可以解决它吗?

我暂时不想更改任何其他代码,因为代码太多而且需要很长时间。我知道这不是很好的做法,但这是一个家庭项目,我只想让线路正常工作,即所有更改都发生在:

tweet = json.loads(mention.strip())

我怀疑这是因为我正在尝试将许多提及中的第一个加载到提及字符串中......而这对于 json.loads() 来说并不正确?

您传递给 myfunction() 的变量 mention 不是字符串。您正在传递一个 Status 对象,它基本上包含推文的所有元素,看起来像这样 https://gist.github.com/dev-techmoe/ef676cdd03ac47ac503e856282077bf2 这就是 strip() 方法失败的原因,因为它仅适用于字符串。

但是,Tweepy 中的 Status 对象确实有一个 属性 可以让您获得一个 JSON 可序列化的项目,然后您可以使用它。

#This is going by the code I see, and on the assumption 'mention' is one tweet
tweet_str = json.dumps(mention._json)

#tweet_str is now a JSON string, so you can try replacing your problematic line with:
tweet = json.loads(tweet_str)

我认为值得注意的是,您不一定必须转换为 JSON。您可以直接访问 Status 对象中的参数,因为它已经有点类似于 JSON,但这取决于用例。正如我相信你说过你在别处写了很多代码,你以后可能会依赖 JSON。

来自 Status 对象的 JSON 上的这个帖子非常有用,如果您仍然卡住,请检查一下

希望对您有所帮助!