其他
这些用 Python 写的牛逼程序/脚本,你玩过吗?
数学算法俱乐部
日期:2020年04月13日
正文共:7341字16图
预计阅读时间:19分钟
来源:数据与算法之美
Manoj Memana Jayakumar, 3000+ 顶
1. 电影/电视剧 字幕一键下载器
2. IMDb 查询/电子表格生成器
Source on GitHub: imdb
3. theoatmeal.com 连载漫画下载器
4. someecards.com 下载器
Akshit Khurana,4400+ 顶
感谢 500 多个朋友在 Facebook 上为我送出的生日祝福
2
31. # Thanking everyone who wished me on my birthday
4
52. import requests
6
73. import json
8
94.
10
115. # Aman s post time
12
136. AFTER = 1353233754
14
157. TOKEN =
16
178.
18
199. def get_posts():
20
2110. """Returns dictionary of id, first names of people who posted on my wall
22
2311. between start and end time"""
24
2512. query = ("SELECT post_id, actor_id, message FROM stream WHERE "
26
2713. "filter_key = others AND source_id = me() AND "
28
2914. "created_time > 1353233754 LIMIT 200")
30
3115.
32
3316. payload = { q : query, access_token : TOKEN}
34
3517. r = requests.get( https://graph.facebook.com/fql , params=payload)
36
3718. result = json.loads(r.text)
38
3919. return result[ data ]
40
4120.
42
4321. def commentall(wallposts):
44
4522. """Comments thank you on all posts"""
46
4723. #TODO convert to batch request later
48
4924. for wallpost in wallposts:
50
5125.
52
5326. r = requests.get( https://graph.facebook.com/%s %
54
5527. wallpost[ actor_id ])
56
5728. url = https://graph.facebook.com/%s/comments % wallpost[ post_id ]
58
5929. user = json.loads(r.text)
60
6130. message = Thanks %s :) % user[ first_name ]
62
6331. payload = { access_token : TOKEN, message : message}
64
6532. s = requests.post(url, data=payload)
66
6733.
68
6934. print "Wall post %s done" % wallpost[ post_id ]
70
7135.
72
7336. if __name__ == __main__ :
74
7537. commentall(get_posts())
76
77…
Tanmay Kulshrestha,3300+ 顶
整理照片
2
3import sys
4
5import os,random,string
6
7#choices=[ Add a name ]
8
9import os
10
11current_directory=os.path.dirname(os.path.abspath(__file__))
12
13from Tkinter import Tk
14
15from easygui import *
16
17import numpy as np
18
19x= os.listdir(current_directory)
20
21new_x=[]
22
23testing=[]
24
25for i in x:
26
27if i.find( . )==-1:
28
29new_x+=[i]
30
31else:
32
33testing+=[i]
34
35x=new_x
36
37g=x
38
39choices=[ Add a name ]+x
40
41y= range(1,len(x)+1)
42
43def get_images_and_labels():
44
45global current_directory,x,y,g
46
47if x==[]:
48
49return (False,False)
50
51image_paths=[]
52
53for i in g:
54
55path=current_directory+ +i
56
57for filename in os.listdir(path):
58
59final_path=path+ +filename
60
61image_paths+=[final_path]
62
63# images will contains face images
64
65images = []
66
67# labels will contains the label that is assigned to the image
68
69labels = []
70
71for image_path in image_paths:
72
73# Read the image and convert to grayscale
74
75img = cv2.imread(image_path,0)
76
77# Convert the image format into numpy array
78
79image = np.array(img, uint8 )
80
81# Get the label of the image
82
83backslash=image_path.rindex( )
84
85underscore=image_path.index( _ ,backslash)
86
87nbr = image_path[backslash+1:underscore]
88
89t=g.index(nbr)
90
91nbr=y[t]
92
93# If face is detected, append the face to images and the label to labels
94
95images.append(image)
96
97labels.append(nbr)
98
99#cv2.imshow("Adding faces to traning set...", image)
100
101#cv2.waitKey(50)
102
103# return the images list and labels list
104
105return images, labels
106
107# Perform the tranining
108
109def train_recognizer():
110
111recognizer = cv2.createLBPHFaceRecognizer()
112
113images, labels = get_images_and_labels()
114
115if images==False:
116
117return False
118
119cv2.destroyAllWindows()
120
121recognizer.train(images, np.array(labels))
122
123return recognizer
124
125def get_name(image_path,recognizer):
126
127global x,choices
128
129#if recognizer== :
130
131# recognizer=train_recognizer()
132
133cascadePath = "haarcascade_frontalface_default.xml"
134
135faceCascade = cv2.CascadeClassifier(cascadePath)
136
137#recognizer=train_recognizer()
138
139x1=testing
140
141global g
142
143print image_path
144
145image = cv2.imread(image_path)
146
147img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
148
149predict_image = np.array(img, uint8 )
150
151faces = faceCascade.detectMultiScale(
152
153img,
154
155scaleFactor=1.3,
156
157minNeighbors=5,
158
159minSize=(30, 30),
160
161flags = http://cv2.cv.CV_HAAR_SCALE_IMAGE
162
163)
164
165for (x, y, w, h) in faces:
166
167f= image[y:y+w,x:x+h]
168
169cv2.imwrite( temp.jpg ,f)
170
171im= temp.jpg
172
173nbr_predicted, conf = recognizer.predict(predict_image[y: y + h, x: x + w])
174
175predicted_name=g[nbr_predicted-1]
176
177print "{} is Correctly Recognized with confidence {}".format(predicted_name, conf)
178
179if conf>=140:
180
181continue
182
183msg= Is this +predicted_name
184
185reply = buttonbox(msg, image=im, choices=[ Yes , No ])
186
187if reply== Yes :
188
189reply=predicted_name
190
191directory=current_directory+ +reply
192
193if not os.path.exists(directory):
194
195os.makedirs(directory)
196
197random_name= .join(random.choice(string.ascii_uppercase + string.digits) for _ in range(7))
198
199path=directory+ +random_name+ .jpg
200
201cv2.imwrite(path,f)
202
203else:
204
205msg = "Who is this?"
206
207reply = buttonbox(msg, image=im, choices=choices)
208
209if reply == Add a name :
210
211name=enterbox(msg= Enter the name , title= Training , strip=True)
212
213print name
214
215choices+=[name]
216
217reply=name
218
219directory=current_directory+ +reply
220
221if not os.path.exists(directory):
222
223os.makedirs(directory)
224
225random_name= .join(random.choice(string.ascii_uppercase + string.digits) for _ in range(7))
226
227path=directory+ +random_name+ .jpg
228
229print path
230
231cv2.imwrite(path,f)
232
233
234
235# calculate window position
236
237root = Tk()
238
239pos = int(root.winfo_screenwidth() * 0.5), int(root.winfo_screenheight() * 0.2)
240
241root.withdraw()
242
243WindowPosition = "+%d+%d" % pos
244
245
246
247# patch rootWindowPosition
248
249rootWindowPosition = WindowPosition
250
251def detect_faces(img):
252
253global choices,current_directory
254
255imagePath = img
256
257faceCascade = cv2.CascadeClassifier(cascPath)
258
259image = cv2.imread(imagePath)
260
261gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
262
263faces = faceCascade.detectMultiScale(
264
265gray,
266
267scaleFactor=1.3,
268
269minNeighbors=5,
270
271minSize=(30, 30),
272
273flags = http://cv2.cv.CV_HAAR_SCALE_IMAGE
274
275)
276
277
278
279print "Found {0} faces!".format(len(faces))
280
281m=0
282
283for (x, y, w, h) in faces:
284
285m+=1
286
287padding=0
288
289f= image[y-padding:y+w+padding,x-padding:x+h+padding]
290
291cv2.imwrite( temp.jpg ,f)
292
293im= temp.jpg
294
295msg = "Who is this?"
296
297reply = buttonbox(msg, image=im, choices=choices)
298
299if reply == Add a name :
300
301name=enterbox(msg= Enter the name , title= Training , strip=True)
302
303print name
304
305choices+=[name]
306
307reply=name
308
309directory=current_directory+ +reply
310
311if not os.path.exists(directory):
312
313os.makedirs(directory)
314
315random_name= .join(random.choice(string.ascii_uppercase + string.digits) for _ in range(7))
316
317path=directory+ +random_name+ .jpg
318
319print path
320
321cv2.imwrite(path,f)
322
323def new(img,recognizer):
324
325imagePath = current_directory+ +img
326
327print imagePath
328
329get_name(imagePath,recognizer)
330
331cascPath = haarcascade_frontalface_default.xml
332
333b=0
334
335os.system("change_name.py")
336
337for filename in os.listdir("."):
338
339b+=1
340
341if b%10==0 or b==1:
342
343os.system("change_name.py")
344
345recognizer=train_recognizer()
346
347if filename.endswith( .jpg ) or filename.endswith( .png ):
348
349print filename
350
351imagePath=filename
352
353#detect_faces(imagePath)
354
355new(imagePath,recognizer)
356
357os.remove(filename)
358
359raw_input( Done with this photograph )
Gmail 邮件通知
(Passenger Name Record旅客订座记录,下同) 状态短讯
YouTube 视频下载器
板球比分通知器
WhatsApp 消息
Nalanda 下载器
2
3start_time = time.time()
4
5from bs4 import BeautifulSoup
6
7br=mechanize.Browser()
8
9br.open( https://nalanda.bits-pilani.ac.in/login/index.php )
10
11br.select_form(nr=0)
12
13
14
15name=
16
17while name== :
18
19 try:
20
21 print *******
22
23 username=raw_input( Enter Your Nalanda Username: )
24
25 password=getpass.getpass( Password: )
26
27 br.form[ username ]=username
28
29 br.form[ password ]=password
30
31 res=br.submit()
32
33 response=res.read()
34
35 soup=BeautifulSoup(response)
36
37 name=str(soup.find( div ,attrs={ class : logininfo }).a.string)[:-2]
38
39 except:
40
41 print Wrong Password
42
43f=open( details.txt , w )
44
45f.write(username+ n +password)
46
47f.close()
48
49print Welcome, +name
50
51print All the files will be downloaded in your Drive C in a folder named "nalanda"
52
53#print soup.prettify()
54
55div=soup.find_all( div ,attrs={ class : box coursebox })
56
57
58l=len(div)
59
60a=[]
61
62for i in range(l):
63
64 d=div[i]
65
66 s=str(d.div.h2.a.string)
67
68 s=s[:s.find( ( )]
69
70 c=(s,str(d.div.h2.a[ href ]))
71
72 path= c:nalanda +c[0]
73
74 if not os.path.exists(path):
75
76 os.makedirs(path)
77
78 a+=[c]
79
80#print a
81
82overall=[]
83
84for i in range(l):
85
86 response=br.open(a[i][1])
87
88 page=response.read()
89
90 soup=BeautifulSoup(page)
91
92 li=soup.find_all( li ,attrs={ class : section main clearfix })
93
94 x=len(li)
95
96 t=[]
97
98 folder=a[i][0]
99
100 print Downloading +folder+ files...
101
102 o=[]
103
104 for j in range(x):
105
106 g=li[j].ul
107
108 #print g
109
110 #raw_input( )
111
112 if g!=None:
113
114 temp=http://g.li[ class ].split( )
115
116 #raw_input( )
117
118 if temp[1]== resource :
119
120 #print yes
121
122 #print ********************
123
124 o+=[j]
125
126 h=li[j].find( div ,attrs={ class : content })
127
128 s=str(h.h3.string)
129
130 path= c:nalanda +folder
131
132 if path[-1]== :
133
134 path=path[:-1]
135
136 path+= +s
137
138 if not os.path.exists(path):
139
140 os.makedirs(path)
141
142 f=g.find_all( li )
143
144 r=len(f)
145
146 z=[]
147
148 for e in range(r):
149
150 p=f[e].div.div.a
151
152 q=f[e].find( span ,attrs={ class : resourcelinkdetails }).contents
153
154 link=str(p[ href ])
155
156 text=str(p.find( span ).contents[0])
157
158 typ=
159
160 if str(q[0]).find( word )!=-1:
161
162 typ= .docx
163
164 elif str(q[0]).find( JPEG )!=-1:
165
166 typ= .jpg
167
168 else:
169
170 typ= .pdf
171
172 if typ!= .docx :
173
174 res=br.open(link)
175
176 soup=BeautifulSoup(res.read())
177
178 if typ== .jpg :
179
180 di=soup.find( div ,attrs={ class : resourcecontent resourceimg })
181
182 link=di.img[ src ]
183
184 else:
185
186 di=soup.find( div ,attrs={ class : resourcecontent resourcepdf })
187
188 link=di.object[ data ]
189
190 try:
191
192 if not os.path.exists(path+ +text+typ):
193
194 br.retrieve(link,path+ +text+typ)[0]
195
196 except:
197
198 print Connectivity Issues
199
200 z+=[(link,text,typ)]
201
202 t+=[(s,z)]
203
204 if t==[]:
205
206 print No Documents in this subject
207
208 overall+=[o]
209
210 #raw_input( Press any button to resume )
211
212#print overall
213
214print Time Taken to Download: +str(time.time()-start_time)+ seconds
215
216print Do you think you can download all files faster than this :P
217
218print Closing in 10 seconds
219
220time.sleep(10)
我自己的 DC++
— THE END —
☞人民币为什么没有3元?原来这是一个数学优化问题☞《线性代数应该这样学》学习小结☞82岁江泽民在2008年发表论文指出:发展智能化,机器学习将有所作为……☞施一公:没有高考,就没有一批非常优秀的社会精英从农村走出来☞知乎热搜可以被人为控制吗?如果可以,怎么操作