Repository navigation
Expand file tree
/
Copy pathproject.py
More file actions
2539 lines (2148 loc) · 80.8 KB
/
Copy pathproject.py
File metadata and controls
2539 lines (2148 loc) · 80.8 KB
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
* 图像扩容
* 贺卡
* 贺卡1
* 贺卡2
* 数据挖掘大作业:产品推荐
* 爬虫模板
* 爬虫解释版
* 爬虫解释版1
* 深圳杯公交车数据处理
* 金融建模第一题
* 股票模板简略版
* 股票策略模版
* 收益率曲线
* 金钗银钗
* 长短线
* CNN图像-分类
* RNN图像-分类-正确版
* RNN图像-分类-原始版
"""
# 图像扩容
"""
'''
1. 翻转变换 flip
2. 随机修剪 random crop
3. 色彩抖动 color jittering
4. 平移变换 shift
5. 尺度变换 scale
6. 对比度变换 contrast
7. 噪声扰动 noise
8. 旋转变换/反射变换 Rotation/reflection
author: XiJun.Gong
date:2016-11-29
'''
from PIL import Image, ImageEnhance, ImageOps, ImageFile
import numpy as np
import random
import threading, os, time
import logging
logger = logging.getLogger(__name__)
ImageFile.LOAD_TRUNCATED_IMAGES = True
class DataAugmentation:
'''
包含数据增强的八种方式
'''
def __init__(self):
pass
@staticmethod
def openImage(image):
return Image.open(image, mode="r")
@staticmethod
def randomRotation(image, mode=Image.BICUBIC):
'''
对图像进行随机任意角度(0~360度)旋转
:param mode 邻近插值,双线性插值,双三次B样条插值(default)
:param image PIL的图像image
:return: 旋转转之后的图像
'''
random_angle = np.random.randint(1, 360)
return image.rotate(random_angle, mode)
@staticmethod
def randomCrop(image):
'''
对图像随意剪切,考虑到图像大小范围(68,68),使用一个一个大于(36*36)的窗口进行截图
:param image: PIL的图像image
:return: 剪切之后的图像
'''
image_width = image.size[0]
image_height = image.size[1]
crop_win_size = np.random.randint(40, 68)
random_region = (
(image_width - crop_win_size) >> 1, (image_height - crop_win_size) >> 1, (image_width + crop_win_size) >> 1,
(image_height + crop_win_size) >> 1)
return image.crop(random_region)
@staticmethod
def randomColor(image):
'''
对图像进行颜色抖动
:param image: PIL的图像image
:return: 有颜色色差的图像image
'''
random_factor = np.random.randint(0, 31) / 10. # 随机因子
color_image = ImageEnhance.Color(image).enhance(random_factor) # 调整图像的饱和度
random_factor = np.random.randint(10, 21) / 10. # 随机因子
brightness_image = ImageEnhance.Brightness(color_image).enhance(random_factor) # 调整图像的亮度
random_factor = np.random.randint(10, 21) / 10. # 随机因1子
contrast_image = ImageEnhance.Contrast(brightness_image).enhance(random_factor) # 调整图像对比度
random_factor = np.random.randint(0, 31) / 10. # 随机因子
return ImageEnhance.Sharpness(contrast_image).enhance(random_factor) # 调整图像锐度
@staticmethod
def randomGaussian(image, mean=0.2, sigma=0.3):
'''
对图像进行高斯噪声处理
:param image:
:return:
'''
def gaussianNoisy(im, mean=0.2, sigma=0.3):
'''
对图像做高斯噪音处理
:param im: 单通道图像
:param mean: 偏移量
:param sigma: 标准差
:return:
'''
for _i in range(len(im)):
im[_i] += random.gauss(mean, sigma)
return im
# 将图像转化成数组
img = np.asarray(image)
img.flags.writeable = True # 将数组改为读写模式
width, height = img.shape[:2]
img_r = gaussianNoisy(img[:, :, 0].flatten(), mean, sigma)
img_g = gaussianNoisy(img[:, :, 1].flatten(), mean, sigma)
img_b = gaussianNoisy(img[:, :, 2].flatten(), mean, sigma)
img[:, :, 0] = img_r.reshape([width, height])
img[:, :, 1] = img_g.reshape([width, height])
img[:, :, 2] = img_b.reshape([width, height])
return Image.fromarray(np.uint8(img))
@staticmethod
def saveImage(image, path):
image.save(path)
def makeDir(path):
try:
if not os.path.exists(path):
if not os.path.isfile(path):
# os.mkdir(path)
os.makedirs(path)
return 0
else:
return 1
except Exception as e:
print
str(e)
return -2
def imageOps(func_name, image, des_path, file_name, times=5):
funcMap = {"randomRotation": DataAugmentation.randomRotation,
# "randomCrop": DataAugmentation.randomCrop,
"randomColor": DataAugmentation.randomColor,
"randomGaussian": DataAugmentation.randomGaussian
}
if funcMap.get(func_name) is None:
logger.error("%s is not exist", func_name)
return -1
for _i in range(0, times, 1):
new_image = funcMap[func_name](image)
DataAugmentation.saveImage(new_image, os.path.join(des_path, func_name + str(_i) + file_name))
opsList = {"randomRotation", "randomColor", "randomGaussian"}
def threadOPS(path, new_path):
'''
多线程处理事务
:param src_path: 资源文件
:param des_path: 目的地文件
:return:
'''
if os.path.isdir(path):
img_names = os.listdir(path)
else:
img_names = [path]
for img_name in img_names:
print
img_name
tmp_img_name = os.path.join(path, img_name)
if os.path.isdir(tmp_img_name):
if makeDir(os.path.join(new_path, img_name)) != -1:
threadOPS(tmp_img_name, os.path.join(new_path, img_name))
else:
print
'create new dir failure'
return -1
# os.removedirs(tmp_img_name)
elif tmp_img_name.split('.')[1] != "DS_Store":
# 读取文件并进行操作
image = DataAugmentation.openImage(tmp_img_name)
threadImage = [0] * 5
_index = 0
for ops_name in opsList:
threadImage[_index] = threading.Thread(target=imageOps,
args=(ops_name, image, new_path, img_name,))
threadImage[_index].start()
_index += 1
time.sleep(0.2)
if __name__ == '__main__':
threadOPS("D:\\作业\\比赛\\美赛\\图像分类结果\\Positive ID",
"D:\\作业\\比赛\\美赛\\图像分类结果\\Positive ID")
"""
# 贺卡
"""
import turtle as t
def bgpic(self, picname=None):
if picname is None:
return self._bgpicname
if picname not in self._bgpics:
self._bgpics[picname] = self._image(picname)
self._setbgpic(self._bgpic, self._bgpics[picname])
self._bgpicname = picname
if __name__ == '__main__':
myWin = t.Screen()
t.setup(width=600, height=750, startx=0, starty=0)
t.bgpic(r'./1.gif')
myWin.exitonclick()
t.bgpic(r'pig.gif')
t.delay(0)
t.setup(1000, 600, 0, 0)
t.up()
t.goto(-50, 0)
t.color("black")
t.write("钟孟诗", font=16)
t.up()
t.hideturtle()
t.done()
"""
# 贺卡1
"""
import turtle as ti
from random import *
from math import *
def tree(n, l):
ti.pd()
t = cos(radians(ti.heading() + 45)) / 8 + 0.25
ti.pencolor(t, t, t)
ti.pensize(n / 3)
ti.forward(l)
if n > 0:
b = random() * 15 + 10
c = random() * 15 + 10
d = l * (random() * 0.25 + 0.7)
ti.right(b)
tree(n - 1, d)
ti.left(b + c)
tree(n - 1, d)
ti.right(c)
else:
ti.right(90)
n = cos(radians(ti.heading() - 45)) / 4 + 0.5
ti.pencolor(n, n * 0.8, n * 0.8)
ti.circle(3)
ti.left(90)
if (random() > 0.7):
ti.pu()
t = ti.heading()
an = -40 + random() * 40
ti.setheading(an)
dis = int(800 * random() * 0.5 + 400 * random() * 0.3 + 200 * random() * 0.2)
ti.forward(dis)
ti.setheading(t)
ti.pd()
ti.right(90)
n = cos(radians(ti.heading() - 45)) / 4 + 0.5
ti.pencolor(n * 0.5 + 0.5, 0.4 + n * 0.4, 0.4 + n * 0.4)
ti.circle(2)
ti.left(90)
ti.pu()
t = ti.heading()
ti.setheading(an)
ti.backward(dis)
ti.setheading(t)
ti.pu()
ti.backward(l)
ti.bgcolor(0.5, 0.5, 0.5)
ti.ht()
ti.speed(0)
ti.tracer(0, 0)
ti.pu()
ti.backward(100)
ti.left(90)
ti.pu()
ti.backward(300)
tree(12, 100)
ti.up()
ti.goto(350, -220)
ti.color("black")
ti.write("黄妍同学,你终将如诗一样美丽", font=16)
ti.up()
ti.goto(430, -260)
ti.color('black')
ti.write("长高高哦", font=16)
ti.up()
ti.goto(650, -370)
ti.color('black')
ti.write("2020年03月26号", move=True)
ti.delay(0)
ti.up()
ti.goto(630, -360)
ti.color('black')
ti.write("《夜深人静》——所制", move=True)
ti.delay(0)
ti.up()
ti.goto(-630, 340)
ti.color('black')
ti.write("声声慢·寻寻觅觅", font=8)
ti.up()
ti.goto(-610, 320)
ti.color('black')
ti.write("[宋] 李清照", font=8)
ti.up()
ti.goto(-680, 300)
ti.color('black')
ti.write("寻寻觅觅,冷冷清清,凄凄惨惨戚戚。", font=8)
ti.up()
ti.goto(-645, 280)
ti.color('black')
ti.write("乍暖还寒时候,最难将息。", font=8)
ti.up()
ti.goto(-675, 260)
ti.color('black')
ti.write("三杯两盏淡酒,怎敌他、晚来风急?", font=8)
ti.up()
ti.goto(-665, 240)
ti.color('black')
ti.write("雁过也,正伤心,却是旧时相识。", font=8, move=True)
ti.up()
ti.goto(-690, 200)
ti.color('black')
ti.write("满地黄花堆积。憔悴损,如今有谁堪摘?", font=8, move=True)
ti.up()
ti.goto(-640, 180)
ti.color('black')
ti.write("守着窗儿,独自怎生得黑?", font=8, move=True)
ti.up()
ti.goto(-670, 160)
ti.color('black')
ti.write("梧桐更兼细雨,到黄昏、点点滴滴。", font=8, move=True)
ti.up()
ti.goto(-640, 140)
ti.color('black')
ti.write("这次第,怎一个愁字了得!", font=8, move=True)
ti.up()
ti.hideturtle()
ti.done()
"""
# 贺卡2
"""
import turtle as t
def bgpic(self, picname=None):
if picname is None:
return self._bgpicname
if picname not in self._bgpics:
self._bgpics[picname] = self._image(picname)
self._setbgpic(self._bgpic, self._bgpics[picname])
self._bgpicname = picname
if __name__ == '__main__':
myWin = t.Screen()
t.setup(width=600, height=750, startx=0, starty=0)
t.bgpic(r'./1.gif')
myWin.exitonclick()
t.bgpic(r'pig.gif')
t.delay(0)
t.setup(1000, 600, 0, 0)
t.colormode(255)
t.pencolor("green")
t.pensize(5)
for i in range(8):
t.circle(50)
t.right(-45)
t.pencolor("red")
t.pensize(5)
for i in range(8):
t.circle(25)
t.right(-45)
t.right(120)
t.circle(-400, 50)
t.penup()
t.goto(-300, -220)
t.pendown()
t.width(25)
t.pencolor("purple")
t.seth(-40)
for i in range(4):
t.circle(40, 80)
t.circle(-40, 80)
t.circle(40, 80/2)
t.fd(40)
t.circle(16, 180)
t.fd(40*2/3)
t.penup()
t.bk(10)
t.pencolor("black")
t.pensize(5)
t.pendown()
t.circle(1, 360)
t.up()
t.goto(150, -120)
t.color("black")
t.write("钟孟诗同学,你终将如诗一样美丽", font=16)
t.up()
t.goto(250, -160)
t.color('black')
t.write("女生节快乐", font=16)
t.up()
t.goto(350, -270)
t.color('black')
t.write("2020年03月07号", move=True)
t.delay(0)
t.up()
t.goto(-485, 240)
t.color('black')
t.write("《清平调·其一》", font=8)
t.up()
t.goto(-430, 220)
t.color('black')
t.write("李白", font=8)
t.up()
t.goto(-480, 200)
t.color('black')
t.write("云想衣裳花想容,", font=8)
t.up()
t.goto(-480, 180)
t.color('black')
t.write("春风拂槛露华浓。", font=8)
t.up()
t.goto(-480, 160)
t.color('black')
t.write("若非群玉山头见,", font=8)
t.up()
t.goto(-480, 140)
t.color('black')
t.write("会向瑶台月下逢。", font=8, move=True)
t.up()
t.hideturtle()
t.done()
"""
# 数据挖掘大作业:产品推荐
"""
import csv
import random
import bisect
class WeightedRandomGenerator(object):
def __init__(self, weights):
self.totals = []
running_total = 0
for w in weights:
running_total += w
self.totals.append(running_total)
def next(self):
rnd = random.random() * self.totals[-1]
return bisect.bisect_right(self.totals, rnd)
def __call__(self):
return self.next()
def eva(num0, num1, datas): #这里其实是为了将他强行写为函数的,方便之后.csv中的内容改了可以继续操作。 num0表示产品型号那一列,num1表示产品故障那一列
eva = [] #这个列表里面存放的是统计数据
exist = [] #这个列表里面存放的是产品型号的顺序,但里面都是产品名
total = [] #为了能够一个函数同时输出刚刚的两个列表,所以我就用一个列表把他们都包起来了。
for data in datas:
ProductName = str(data[num0])
ErrorName = str(data[num1])
if ProductName not in exist:
d = {}
count = 1
d[ErrorName] = count
exist.append(ProductName)
eva.append(d)
else:
product = exist.index(data[num0])
if ErrorName not in eva[product]:
count_another = 1
eva[product][ErrorName] = count_another
else:
eva[product][ErrorName] += 1 #要注意把序列号的方括号卸载外面
total.append(eva)
total.append(exist)
return total
def score(eva):
scores = []
for example in eva:
sum = 0
d_sc = {}
for test in example:
sum += example[test]
for test in example:
score = 100 * (example[test] / sum)
score = round(score,3)
d_sc[test] = score
scores.append(d_sc)
return scores
def sim(scores,exist,w): #scores是各个评分组成的字典所组成的列表,exist是各个项目的列表。两者从序号上一一对应。w表示应当采用那种计算方式。
final = {}
for test in exist:
similarity = {}
train_scores = list(scores)
train_exist = list(exist)
i = exist.index(test)
test_score = train_scores[i] #要注意这个时候test_score已经是一个字典了,而train_score中依然是很多字典组成的列表。
train_scores.pop(i)
train_exist.pop(i)
if w==1: #1表示采用余弦相似度。
for train in train_scores: #这里的每个train还是一个训练集中的一个字典
k = train_scores.index(train)
name = train_exist[k]
sum_pixqi = 0 #这个表示余弦相似度的分子
sum_pi = 0 #这个表示余弦相似度中分子的测试集的那一项
sum_qi = 0 #这个表示余弦相似度中分子的训练集的那一项
for test_need in test_score:
sum_pi += test_score[test_need]
if test_need in train:
sum_qi += train[test_need]
sum_pixqi += (train[test_need] * test_score[test_need])
else:
sum_qi += 0.50
sum_pixqi += (test_score[test_need] * 0)
cos = (sum_pixqi / (sum_pi * sum_qi)) ** (1/2)
cos_3 = round(cos,3)
similarity[name] = cos_3
final[test] = similarity
return final
def cop(scores,exist): #这个方法是用来合并名称和分数的,最后会得到一个字典
copd = {}
for a in exist:
number = exist.index(a)
content = scores[number]
copd[a] = content
return copd
def prodict(cop, sim, exist):
prodict = {}
for Product in exist:
recommend = []
sim_Product = sim[Product] #把产品的相似度字典抽出来
score_Product = cop[Product] #把产品的分数抽出来
sort_sim_groupDict = sorted(sim_Product.items(), key= lambda item:item[1], reverse= True)
sort_sim = {i[0]:i[1] for i in sort_sim_groupDict}
recommend_dict = {}
for key,value_sim in sort_sim.items():
score_sim_Product = cop[key]
sort_score_sim_groupDict = sorted(score_sim_Product.items(), key=lambda item: item[1], reverse=True)
sort_score_sim_Product = {i[0]: i[1] for i in sort_score_sim_groupDict}
count = 0
for ErrorName in sort_score_sim_Product:
if ErrorName not in score_Product:
score_need = sort_score_sim_Product[ErrorName] * sort_sim[key]
recommend_dict[ErrorName] = score_need
count += 1
if count >= 5:
break
sort_recommend_groupDict = sorted(recommend_dict.items(), key=lambda item: item[1], reverse=True)
sort_recommend_dict = {i[0]: i[1] for i in sort_recommend_groupDict}
for i in sort_recommend_dict.keys():
recommend.append(i)
recommend_wash = list(set(recommend)) #清洗数据
recommend_wash.sort(key=recommend.index) #清洗数据之后排序
recommend_indeed = []
for i in range(len(recommend_wash)):
recommend_indeed.append(recommend_wash[i]) # 将算法得到的前三个故障推荐出去
prodict[Product] = recommend_indeed
return prodict
file = open("op_1.csv")
datas = csv.reader(file)
eva_all = eva(0,1,datas) #先填0,再填1,是用型号评分故障;如果先填1,再填0,就是用故障评分型号
need = eva_all[0]
exist = eva_all[1]
scores = score(need)
copx = cop(scores, exist)
simx = sim(scores,exist,1)
prodictx = prodict(copx, simx, exist)
# print("通过协同过滤推荐算法,以下设备可能出现的故障是:")
# for i in prodictx:
# print(str(i) + ": " + prodictx[i][0] + " 或 " + prodictx[i][1] + " 或 " + prodictx[i][2])
# 对于得到数据排序
need_change=[]
need_change_end=[]
exist_change=[]
for i in range(len(need)):
if len(need[i])>10:
need_change.append(need[i])
exist_change.append(exist[i])
for i in range(len(need_change)):
need_change_end.append(sorted(need_change[i].items(),key=lambda d:d[1],reverse=True))
# 测试集的数据点
need_change_qz=[]
need_change_sum=[]
for i in range(len(need_change_end)):
sum = 0
need_change_test = []
for j in range(len(need_change_end[i])):
sum+=need_change_end[i][j][1]
need_change_test.append(need_change_end[i][j][1])
need_change_qz.append(need_change_test)
need_change_sum.append(sum)
need_change_qz_end=[]
for i in range(len(need_change_qz)):
if len(need_change_qz[i])>10:
num=0
d_test = {}
test = WeightedRandomGenerator(need_change_qz[i])
for j in range(need_change_sum[i]//5): #取1/5为测试集
test_work=test.__call__()
for key in d_test:
if test_work==key:
num=1
if num==1:
d_test[test_work]+=1
else:
d_test[test_work]=1
num=0
need_change_qz_end.append(d_test)
need_test_end=[]
for i in range(len(need_change_qz_end)):
need_test_end.append(sorted(zip(need_change_qz_end[i].keys(), need_change_qz_end[i].values())))
need_end=[]
need_begin=[]
for i in range(len(need_test_end)):
need_dt={}
need_dtb={}
num1 = 0
leng = len(need_test_end[i])-1
for j in range(len(need_change_end[i])):
k = need_test_end[i][num1][0]
if j==k:
need_dt[need_change_end[i][j][0]]=need_change_end[i][j][1]-need_test_end[i][num1][1]
need_dtb[need_change_end[i][j][0]]=need_test_end[i][num1][1]
if num1<leng:
num1+=1
else:
need_dt[need_change_end[i][j][0]]=need_change_end[i][j][1]
need_end.append(need_dt)
need_begin.append(need_dtb)
# 去掉孤点测试集-need_begin
# 去点孤点验证集-need_end
# 减去孤点产品符号-exist_change
# 减去孤点原本集-need_change
pro_change = []
for i in range(len(need_begin)):
pro_num = 0
pro_num_test = 0
need_retain = need_change[i]
need_change[i] = need_begin[i]
scores_change = score(need_change)
cop_change = cop(scores, exist)
sim_change = sim(scores_change, exist_change, 1)
prodict_change = prodict(cop_change, sim_change, exist_change)
# for key in prodict_change:
# if pro_num_test == i:
# print(prodict_change[key])
# pro_num_test += 1
for pro in prodict_change:
if pro_num_test == i:
print(prodict_change[pro])
print(need_end[i])
for key in need_end[i]:
for cont in prodict_change[pro]:
if key == cont:
pro_num += 1
pro_num_test += 1
print(pro_num)
# if pro_num >= 5:
# pro_change.append(prodict_change[i])
# need_change[i]=need_retain
# for i in pro_change:
# print(str(i) + ": " + prodict_change[i][0] + " 或 " + prodict_change[i][1] + " 或 " + prodict_change[i][2])
# for i in prodictx:
# print(str(i) + ": " + prodictx[i][0] + " 或 " + prodictx[i][1] + " 或 " + prodictx[i][2])
"""
# 爬虫模板
"""
# -*- codeing = utf-8 -*-
# 导入模块
import requests
'''网页解析,获取数据'''
from bs4 import BeautifulSoup
'''正则表达式,进行文字匹配'''
import re
'''制定URL,获取网页数据'''
import urllib.request
import urllib.error
'''解析器'''
import urllib.parse
'''进行Excel操作'''
import xlwt
'''进行数据库操作'''
import sqlite3
'''流程:'''
'''
1、爬取网页
2、解析数据
3、保存数据
'''
def url_open(url): # 打开每个地址
# 添加header,伪装成浏览器
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"}
res = requests.get(url, headers=headers)
return res
# 创建三个储存信息的列表
name_list = []
info_list = []
rate_list = []
# 获取电影名字
def get_name(soup, name_list):
targets = soup.find_all("div", class_="hd")
for each in targets:
name_list.append(each.a.span.text)
# 获取电影信息
def get_info(soup, info_list):
targets = soup.find_all("div", class_='bd')
for each in targets:
try:
info_list.append(each.p.text.split('\n')[1].strip() + each.p.text.split('\n')[2].strip())
except:
continue
# 获取电影评分
def get_rate(soup, rate_list):
targets = soup.find_all("span", class_="rating_num")
for each in targets:
rate_list.append(each.text)
# 将获取信息写入TXT文件
def write_into(name_list, info_list, rate_list):
with open("豆瓣Top250电影.txt", "w", encoding="utf-8") as f:
for i in range(250):
f.write(name_list[i] + ' 评分:' + rate_list[i] + ' ' + info_list[i] + '\n\n')
url = []
for i in range(10): # 得到十个页面地址
url.append("https://movie.douban.com/top250?start=%d&filter=" % (i * 25))
def main():
# 遍历每个页面链接并获取信息
for each_url in url:
res = url_open(each_url)
soup = BeautifulSoup(res.text, "html.parser")
get_name(soup, name_list)
get_info(soup, info_list)
get_rate(soup, rate_list)
write_into(name_list, info_list, rate_list)
# 该模块既可以导入到别的模块中使用,另外该模块也可自我执行
'''定义程序入口、执行第一个函数、主程序开始点'''
if __name__ == "__main__":
'''当我们程序执行时,调用函数'''
'''目的:为了控制函数调用流程'''
'''此刻调用的就是主程序函数'''
main()
for i in range(100):
print(name_list[i] + " " + info_list[i] + " " + rate_list[i])
"""
# 爬虫解释版
"""
#!/爬虫/bin/env python
# -*- coding: utf-8 -*-
'''网页解析,获取数据'''
from bs4 import BeautifulSoup
'''正则表达式,进行文字匹配'''
import re
'''制定URL,获取网页数据'''
import urllib.request
import urllib.error
'''解析器'''
import urllib.parse
'''进行Excel操作'''
import xlwt
'''进行数据库操作'''
import sqlite3
'''流程:'''
'''
1、爬取网页
2、解析数据
3、保存数据
'''
# 影片详细链接
findLink = re.compile(r'<a href="(.*?)">')
# 影片图片
findImgSrc = re.compile(r'<img .* src="(.*?)"', re.S) # re.S:让换行符包含在字符中
# 影片片名
findTitle = re.compile(r'<span class="title">(.*)</span>')
# 影片其他名
findTitle_other = re.compile(r'<span class="other">(.*)</span>')
# 影片评分
findRating = re.compile(r'<span class="rating_num" property="v:average">(.*)</span>')
# 评价人数
findJudge = re.compile(r'<span>(\d*)人评价</span>')
# 概况
findInq = re.compile(r'<span class="inq">(.*)</span>')
# 影片相关内容
findBd = re.compile(r'<p class="">(.*?)</p>', re.S)
def main():
baseurl = "https://movie.douban.com/top250?start="
data_list = getData(baseurl)
save_path = "豆瓣电影Top250.xls"
saveData(data_list, save_path)