AttributeError:'unicode'对象没有属性'has_key'

时间:2014-05-08 19:29:30

标签: python json twitter

我一直在研究一些代码来解析Twitter数据(不是程序员),现在我遇到了另一个我无法弄清楚的错误。

我的目标是从命令行调用此函数:`cat file.json | python main.py> output.csv'。我还没有完成很多功能,但希望我只是有一个简单的错误。

错误

Traceback (most recent call last):
  File "/home/titan/Titan_share/Titan/twitterAPI/printTweets_v7.py", line 34, in <module>
    main()
  File "/home/titan/Titan_share/Titan/twitterAPI/printTweets_v7.py", line 21, in main
    if tweet.has_key('retweeted_status'):
AttributeError: 'unicode' object has no attribute 'has_key'

代码

import json
import sys
import time

def main():

    for line in sys.stdin:
        line = line.strip()

        data = ''
        try:
            data = json.loads(line)
        except ValueError as detail:
            continue

        for tweet in data:

            tweet_time = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(data['created_at'],'%a %b %d %H:%M:%S +0000 %Y'))

            ## if the key 'retweeted_status' is in the dict, print 
            if tweet.has_key('retweeted_status'):
                print tweet_time , "\t" , tweet['id_str'], "\t" , tweet['user']['screen_name'] , "\t" , tweet['retweeted_status']['user']['screen_name'] , "\t" , "RETWEET" , "\t" , tweet['text']

            ## if there is a mention in the dict, print
            elif 'entities' in tweet and len(tweet['entities']['user_mentions']) > 0:
                for u2 in tweet['entities']['user_mentions']:
                    print tweet_time , "\t" , tweet['id_str'], "\t" , tweet['user']['screen_name'] , "\t" , u2['screen_name'] , "\t" , "MENTION" , "\t" , tweet['text']

            ## if there is no retweet and no mention, print
            else:
                print tweet_time , "\t" , tweet['id_str'], "\t" , tweet['user']['screen_name'] , "\t" , "\t" , "TWEET" , "\t" , tweet['text']

if __name__ == '__main__':
    main()

0 个答案:

没有答案