forked from jyfc/ebook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generateTOC.py
112 lines (91 loc) · 3.2 KB
/
generateTOC.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#!/usr/bin/env python
# coding=utf-8
import os
import sys
import requests
import json
class DoubanBookApi:
base_url = 'https://api.douban.com/v2/book/'
keyword = 'bookname'
search_url = base_url + 'search?q=' + keyword + '&fields=id,title,rating,url'
subject_url = 'https://book.douban.com/subject/'
@classmethod
def SearchUrl(cls, bookname):
return cls.search_url.replace(cls.keyword, bookname)
@classmethod
def BookUrl(cls, bookid):
return cls.subject_url + str(bookid)
class DoubanBook:
# douban api 限制请求次数和频率. 不使用代理,置为 None
proxies = {'https': "https://186.170.31.134:8080", }
def __init__(self, name):
if os.name == 'posix':
self.name = name
else:
self.name = name.decode('gbk').encode('utf8')
def SearchBook(self):
try:
response = requests.get(
DoubanBookApi.SearchUrl(self.name),
proxies=self.proxies)
json_data = json.loads(response.text)
books = json_data['books']
first = books[0]
self.rating = first['rating']['average']
self.id = first['id']
self.url = first['url']
except Exception as e:
#print e.message, e.args
self.rating = None
self.id = None
self.url = None
def Name(self):
return self.name
def Rating(self):
return self.rating
def Id(self):
return self.id
def Url(self):
return DoubanBookApi.BookUrl(self.id)
class TOC:
scriptName = os.path.basename(__file__)
scriptDir = os.path.dirname(os.path.realpath(__file__))
output_file = 'readme.md'
output_path = os.path.join(scriptDir, output_file)
exclude_files = [output_file, scriptName]
exclude_dirs = []
preface = '''
# 计算机专业书籍
**注:尊重知识产权,购买正版!这些电子文档均来自网络,如有侵权,请联系我予以删除。**
auto-generated by %s
******
''' % (scriptName)
@classmethod
def generate(cls):
fd = file(cls.output_path, 'w')
orig_stdout = sys.stdout
sys.stdout = fd
print cls.preface
startpath = cls.scriptDir
for root, dirs, files in os.walk(startpath):
files = [f for f in files
if f[0] != '.' and f not in cls.exclude_files]
dirs[:] = [d for d in dirs
if d[0] != '.' and d not in cls.exclude_dirs]
level = root.replace(startpath, '').count(os.sep)
header = '#' * (level + 1) + ' '
print('\n{}{}/\n'.format(header, os.path.basename(root)))
list_n = 0
for f in files:
list_n += 1
f = os.path.splitext(f)[0]
a = DoubanBook(f)
a.SearchBook()
item = '{}. {} [Douban {}]({})'.format(list_n, f, a.Rating(),
a.Url())
if os.name == 'posix':
print item
else:
print item.decode('gbk').encode('utf-8')
sys.stdout = orig_stdout
TOC.generate()