2017-02-19 3 views
-1

Следующий код используется для печати имя пользователя, идентификатор, длинные, лат твиты и ничего не отображаетсящебет данных с помощью питона

import json 
import re 

tweets_data_path = '/home/anusri/pythonpractice/x.json' 

tweets_data = [] 

tweets_file = open(tweets_data_path, "r") 

for line in tweets_file: 
    try: 
     tweet = json.loads(line) 
     tweets_data.append(tweet) 
     print tweet['user']['id_str'] + "," + tweet['user']['name'] + "," + tweet['bounding_box']['coordinates'][0] + "," + tweet['bounding_box']['coordinates'][1] 

except: 
     continue 

Файл JSON является

{"created_at":"Sun Feb 19 10:53:16 +0000 2017","id":833268205040709632,"id_str":"833268205040709632","text":"Rewa supermarket didn\u2019t have my go to cold & flu medicine or that cold pressed honey ginger apple drink that I love #shoregirlproblems","source":"\u003ca href=\"http:\/\/tapbots.com\/tweetbot\" rel=\"nofollow\"\u003eTweetbot for i\u039fS\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":179399275,"id_str":"179399275","name":"K","screen_name":"winesandlines","location":"The Comeback Tour","url":"http:\/\/www.stuff.co.nz\/the-press\/news\/6953483\/Tweeter-cops-it-for-breastfeed-photo-post","description":"Most hated NZ twitter user as voted by media outlets \/\/ internalized ageism and voted by Wgtn twitter to most likely be a homophobe #yammygang Nick Jonas stan","protected":false,"verified":false,"followers_count":610,"friends_count":570,"listed_count":17,"favourites_count":22797,"statuses_count":108859,"created_at":"Tue Aug 17 05:26:14 +0000 2010","utc_offset":46800,"time_zone":"Nuku'alofa","geo_enabled":true,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"131516","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme14\/bg.gif","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme14\/bg.gif","profile_background_tile":true,"profile_link_color":"009999","profile_sidebar_border_color":"EEEEEE","profile_sidebar_fill_color":"EFEFEF","profile_text_color":"333333","profile_use_background_image":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/742544496135524352\/pEhwRiBa_normal.jpg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/742544496135524352\/pEhwRiBa_normal.jpg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/179399275\/1454402348","default_profile":false,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":{"type":"Point","coordinates":[-37.03983412,174.87964210]},"coordinates":{"type":"Point","coordinates":[174.87964210,-37.03983412]},"place":{"id":"0022e3c837579650","url":"https:\/\/api.twitter.com\/1.1\/geo\/id\/0022e3c837579650.json","place_type":"city","name":"Auckland","full_name":"Auckland, New Zealand","country_code":"NZ","country":"New Zealand","bounding_box":{"type":"Polygon","coordinates":[[[174.161834,-37.292621],[174.161834,-35.898837],[175.550653,-35.898837],[175.550653,-37.292621]]]},"attributes":{}},"contributors":null,"is_quote_status":false,"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[{"text":"shoregirlproblems","indices":[121,139]}],"urls":[],"user_mentions":[],"symbols":[]},"favorited":false,"retweeted":false,"filter_level":"low","lang":"en","timestamp_ms":"1487501596113"} 
+0

Спасибо, но нет никакой разницы – chocopie

+0

ли ваш файл JSON состоит из одной строки? Также распечатайте исключение, пойманное – ZdaR

+0

Нет, его несколько строк атрибутов относительно одного твиттера твиттера. – chocopie

ответ

0

Ну Были некоторые основные ошибки в коде, json.loads() берет всю правильно отформатированную строку JSON в качестве входных данных, поэтому нет смысла читать файл по строкам и вызывать json.loads(), если у вас нет допустимых JSON в каждой строке, что здесь не так.

Во-вторых, вы пытались получить доступ к "coordinates" поданным неправильно, если он находится в качестве детей "place". Таким образом, окончательный код может выглядеть следующим образом:

import json 

tweets_data = [] 
tweets_data_path = '/home/anusri/pythonpractice/x.json' 

# Read the whole file at once. 
tweets_content = open(tweets_data_path, "r").read() 

try: 
    tweet = json.loads(tweets_content) 
    tweets_data.append(tweet) 
    print tweet['user']['id_str'] + "," + tweet['user']['name'] + "," + str(tweet["place"]['bounding_box']['coordinates']) 
except Exception as e: 
    print "Exception Caught : ", e 
+0

Да! Благодаря тонну. – chocopie

Смежные вопросы