我一直收到KeyError:'消息',我不确定为什么?
以下是我正在解析的数据示例:
{
"data": [
{
"id": "86264418970_10152060349923971",
"from": {
"category": "Health/beauty",
"category_list": [
{
"id": "181045748599578",
"name": "Personal Trainer"
}
],
"name": "Infinite Fitness - Personal Training",
"id": "86264418970"
},
"to": {
"data": [
{
"category": "Kitchen/cooking",
"category_list": [
{
"id": "132852590115660",
"name": "Kitchen Supplies"
},
{
"id": "150060378385891",
"name": "Appliances"
}
],
"name": "Vitamix",
"id": "89031985873"
}
]
},
"message": "Favourite Things Friday! \nThis a new feature for 2014. Every Friday will feature a product, business, person, quote, etc that is our absolute favourite!! If you have ideas or want to share your favourite thing, let us know.\n\nThis week, it's the Vitamix! Honestly it's the one kitchen appliance that I just can't live without. Although shakes are nothing new in our world, the degree to which the Vitamix blends is incomparable to anything I've seen. It has made adding a variety of veggies (broccoli, spinach, kale, beets, carrots) a breeze as it blends to a completely smooth consistency. \n\nBonus points, the kids LOVE the shakes and little do they know all the amazing things they're getting with it. \nExtra bonus points, although I don't do it often, I have made soup and ice cream with it. Super easy.\nExtra extra bonus points, clean up is a snap! Less than a minute, no joke.\n\n(The favourite things feature is my own opinion and although I gush, I am not being paid to do so)",
"message_tags": {
"245": [
{
"id": "89031985873",
"name": "Vitamix",
"type": "page",
"offset": 245,
"length": 7
}
]
},
"privacy": {
"value": ""
},
"type": "status",
"application": {
"name": "Pages Manager for iOS",
"namespace": "fbpagemanager_ios",
"id": "165907476854626"
},
"created_time": "2014-01-10T15:01:41+0000",
"updated_time": "2014-01-10T15:01:41+0000"
},
{
"id": "7568536355_10102570693591239",
"from": {
"category": "Computers/internet website",
"name": "Lifehacker",
"id": "7568536355"
以下是我的代码:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import csv
import json
import urllib
import sys
import time
import re
class FacebookSearch(object):
def __init__(self):
self.url_format = 'https://graph.facebook.com/search?{query}&{type}&{access_token}'
self.access_token = 'access_token=XXXXXXXXX|XXXXXXX'
def make_search_url(self, q, type='post', **queryargs):
queryargs['q'] = q
query = urllib.urlencode(queryargs)
url = self.url_format.format(query=query, type=type,
access_token=self.access_token, **queryargs)
return url
def search(self, q, type='post', **queryargs):
url = self.make_search_url(q, **queryargs)
page = urllib.urlopen(url)
return page.read()
def write_csv(fname, rows, header=None, append=False, **kwargs):
filemode = 'ab' if append else 'wb'
with open(fname, filemode) as outf:
out_csv = csv.writer(outf, **kwargs)
if header:
out_csv.writerow(header)
out_csv.writerows(rows)
def main():
ts = FacebookSearch()
data = ts.search('appliance')
js = json.loads(data)
messages = ([msg['created_time'].replace('T', ' ').replace('+0000', ''), msg['message'].replace('\n', ' ').encode('utf8'), msg['from']['id']] for msg in js.get('data', []))
write_csv('fb_washerdryer.csv', messages, append=True)
if __name__ == '__main__':
main()
以下是错误的完整追溯:
[ec2-user @ ip-172-31-46-164~] $ ./facebook_washer_dryer4.sh Traceback (最近一次调用最后一次):文件“./facebook_washer_dryer4.sh”,行 47,在 main()文件“./facebook_washer_dryer4.sh”,第44行,在main中 write_csv('fb_washerdryer.csv',messages,append = True)文件“./facebook_washer_dryer4.sh”,第35行,在write_csv中 out_csv.writerows(rows)文件“./facebook_washer_dryer4.sh”,第42行,in messages =([msg ['created_time']。replace('T','')。replace('+ 0000',''),msg ['message']。replace('\ n',' ')。encode('utf8'),msg ['from'] ['id']]用于js.get中的msg('data',[])) KeyError:'message'[ec2-user @ ip-172-31-46-164~] $
我已经回顾了json我正在解析一边然后回到另一边而我不明白为什么我会得到一个“Key Value error”。
我一直试图解决这个问题2天,并且真的想找到解决方案。任何帮助或建议将不胜感激
答案 0 :(得分:2)
尝试用msg['message']
替换msg.get('message', 'Key "message" is not present.')
,然后打印messages
。
可能并非数据中的所有消息都包含消息密钥。使用get()
将导致代码在列表理解的中间不会中断,允许您在之后检查结果。