Skip to content

Instantly share code, notes, and snippets.

@Ulu2005
Last active January 8, 2018 07:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Ulu2005/7d6f9cf06b3b9a3c35ab38d065d95610 to your computer and use it in GitHub Desktop.
Save Ulu2005/7d6f9cf06b3b9a3c35ab38d065d95610 to your computer and use it in GitHub Desktop.
douban book yearly report
#!/usr/bin/env python3
import json
import urllib.request
YEAR = 2017
USER_ID = '替换ID'
BASE_URL = 'https://api.douban.com/v2/book/user/{}'.format(USER_ID)
DATE_RANGE = 'from={}-01-01T00:00:00+08:00&to={}-12-31T23:59:59+08:00'.format(
YEAR, YEAR)
REPORT = '{}年一共阅读{}本书\n总计{}页,平均每天{}页\n这些书籍价值{}元\n读过最厚的书是{}页的《{}》'
def fetch_books():
user_books_url = '{}/collections?status=read&{}'.format(
BASE_URL, DATE_RANGE)
response = urllib.request.urlopen(url=user_books_url)
if response.status != 200:
print(response.status, response.reason, sep=' ')
exit()
books = json.loads(response.read().decode('utf-8'))
return books
def generate_report(books):
total_num = int(books['total'])
total_pages = 0
total_price = 0.0
thickest_book = ''
thickest_book_page = -1
for book in books['collections']:
book = book['book']
if book['pages'] == '':
page = 0
print(book['title'], ' 缺少页码信息.\n\n')
else:
page = int(book['pages'])
total_pages += page
if page > thickest_book_page:
thickest_book = book['title']
thickest_book_page = page
total_price += float(book['price'].replace('元', '').replace('CNY', ''))
daily_pages = total_pages / 365
report = REPORT.format(
YEAR, total_num,
total_pages, daily_pages,
total_price,
thickest_book_page, thickest_book)
print(report)
if __name__ == '__main__':
books = fetch_books()
generate_report(books)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment