标签:elf 9.1 eve return url uil sorted download pat
#19.1 使用动态属性转换数据
"""
#栗子19-2 osconfeed.py:下载 osconfeed.json
from urllib.request import urlopen
import os
import warnings
import json
import sys
URL = ‘http://www.oreilly.com/pub/sc/osconfeed‘
JSON = ‘data/osconfeed.json‘
path = os.path.join(sys.path[0],JSON)
path = path.replace(‘\\‘,‘/‘)
def load():
if not os.path.exists(path):
msg = ‘downloading {} to {}‘.format(URL,path)
warnings.warn(msg)
with urlopen(URL) as remote,open(path,‘wb‘) as local:
local.write(remote.read())
with open(path,‘rb‘) as fp:
return json.load(fp)
feed = load()
print(sorted(feed[‘Schedule‘].keys())) #[‘conferences‘, ‘events‘, ‘speakers‘, ‘venues‘]
for key,value in sorted(feed[‘Schedule‘].items()):
print(‘{:3} {}‘.format(len(value),key))
‘‘‘
1 conferences
494 events
357 speakers
53 venues
‘‘‘
print(feed[‘Schedule‘][‘speakers‘][-1][‘name‘]) #Carina C. Zona
print(feed[‘Schedule‘][‘speakers‘][-1][‘serial‘]) #141590
print(feed[‘Schedule‘][‘events‘][40][‘name‘]) #There *Will* Be Bugs
print(feed[‘Schedule‘][‘events‘][40][‘speakers‘]) #[3471, 5199]
"""
#栗子19-5 通过“点儿”来调用属性
from urllib.request import urlopen
import os
import warnings
import json
import sys
URL = ‘http://www.oreilly.com/pub/sc/osconfeed‘
JSON = ‘data/osconfeed.json‘
path = os.path.join(sys.path[0],JSON)
path = path.replace(‘\\‘,‘/‘)
JSON1 = ‘data/osconfeed1.json‘
path1 = os.path.join(sys.path[0],JSON1)
path1 = path1.replace(‘\\‘,‘/‘)
def load():
if not os.path.exists(path):
msg = ‘downloading {} to {}‘.format(URL,path)
warnings.warn(msg)
with urlopen(URL) as remote,open(path,‘wb‘) as local:
local.write(remote.read())
with open(path1,‘rb‘) as fp:
return json.load(fp)
from collections import abc
class FrozenJSON:
def __init__(self, mapping):
self.__data = dict(mapping)
def __getattr__(self, name):
if hasattr(self.__data, name):
return getattr(self.__data, name)
else:
return FrozenJSON.build(self.__data[name])
@classmethod
def build(cls, obj):
if isinstance(obj, abc.Mapping):
return cls(obj)
elif isinstance(obj, abc.MutableSequence):
return [cls.build(item) for item in obj]
else:
return obj
raw_feed = load()
feed = FrozenJSON(raw_feed)
print(len(feed.Schedule.speakers))
标签:elf 9.1 eve return url uil sorted download pat
原文地址:http://www.cnblogs.com/suren2017/p/7779254.html