实战:RJ爬虫并上传本地SQL
下载了上百个RJ后,如何根据声优或分类喜好来找到自己喜欢的作品就成了个问题,于是诞生出了这个代码 问题拆分 定位需求 查询RJ主要是在对该RJ文件夹对应网页中的标题、声优、制作社团与分类,拿到具体数据后,对数据进行查询操作。 ...
下载了上百个RJ后,如何根据声优或分类喜好来找到自己喜欢的作品就成了个问题,于是诞生出了这个代码 问题拆分 定位需求 查询RJ主要是在对该RJ文件夹对应网页中的标题、声优、制作社团与分类,拿到具体数据后,对数据进行查询操作。 ...
#四位数数字字母验证码,显示进行输入判断验证 from PIL import Image, ImageFilter, ImageFont,ImageDraw import os import random import string import matplotlib.pyplot as plt # ImageFilter:Python中的图像滤波,主要对图像进行平滑、锐化、边界增强等滤波处理。 #随机选取一个数字字母,含大小写 def get_word(): word = string.ascii_letters+string.digits return random.choice(word) #字体像素随机颜色 def font_color(): #random.randint()在范围内取随机数 return(random.randint(32,255),random.randint(23,255),random.randint(32,255)) #背景像素随机颜色 def b_color(): return(random.randint(64,255),random.randint(64,255),random.randint(64,255)) #生成验证码图像,返回一个字符串,表示验证码 def imag(path): w = 60*4 h = 60 d_word='' #新建图像对象 img = Image.new('RGB',(w,h),(255,255,255)) #字体对象 font = ImageFont.truetype(r'H:\gay化\汉化\字体\4书法 - 2\FZ宋s刻d本r秀d楷繁.ttf',60) #类似于画笔 draw = ImageDraw.Draw(img) for i in range(w): for j in range(h): #画背景,用随机颜色填充每个像素 draw.point((i,j),fill=b_color()) for i in range(4): word=get_word() #draw.text方法进行字符绘图,()内:绘图位置,字符,字体,颜色 draw.text((i*60+10,5),word,font=font,fill=font_color()) #单个验证码相加 d_word = d_word + word #保存验证码图像 img.save(path,'jpeg') #返回验证码 return d_word #一个输入函数,调用时返回输入内容 def get_input(): return str(input('请输入验证码:\n')) #运行 if __name__ == "__main__": path = ('test.jpg') str_=imag(path) test_img=Image.open(path) plt.figure('test') plt.imshow(test_img) plt.show() #四次机会 for i in range(4): if str.lower(str_) == str.lower(get_input()): print('验证成功') break else: if i == 3: print('错误次数已用完!') else: print('错误!还有%d次机会'%(3-i)) #结束后删除验证码图像 os.remove(path)
#设定一个分辨率,使一个文件夹内所有大于该分辨率的图像都进行等比例缩放 import os import re from PIL import Image #设置目录 f_path = 'E:/vscode/code/testwork/testFile' #设置iPhone5的分辨率 i_high = 640 i_width = 1136 #使用os.listdir()方法,将目录内的图像文件名,以列表的形式存入list list=os.listdir(f_path) #设置计数初始值 count = 0 #对每个文件进行判断 for pic in list: #path为完整的图像文件路径 path=f_path+'/'+pic #使用Image.open()方法,打开图像文件 im=Image.open(path) #im.size方法获得图像的宽高,分别存入w,h w,h=im.size #当宽度大于i5 if w > i_width: #这里判断:原图像哪边大则依据哪边作为等比缩放比例 if w>h: w_new = i_width h_new = int(h*i_width/w) else: w_new = int(w*i_high/h) h_new = i_high print('%s被修改' %pic) #使用resize()方法修改分辨率,((w,h),此处Image.ANTIALIAS表示高质量) out = im.resize((w_new,h_new),Image.ANTIALIAS) #使用re.sub方法,在字符串pic中,开头至倒数第四位字符替换为添加_new的字符串 newpic = re.sub(pic[:-4],pic[:-4]+'_new',pic) #处理后的图像的完整保存路径 new_path = f_path+'/'+newpic #save方法保存 out.save(new_path) #处理完毕计数+1 count = count + 1 elif h > i_high: if w>h: w_new = i_width h_new = int(h*i_width/w) else: w_new = int(w*i_high/h) h_new = i_high print('%s被修改' %pic) out = im.resize((w_new,h_new),Image.ANTIALIAS) newpic = re.sub(pic[:-4],pic[:-4]+'_new',pic) new_path = f_path+'/'+newpic out.save(new_path) count = count + 1 print('处理结束\n总共有%d个文件被处理' %count)
最开始的看到的python基础习题之一,现在顺便扩展一点,练习xlrd、pandas以及matplotlib的练习 数据来源 来自于联通官网的通话数据下载,文件为某年某月的通话记录详情,格式为xls**[图片缺失: 2020/06/QQ截图20200627215145.png]** ...
#2020/3/10 #设置一个屏蔽词文本,输入一段字符串,将其中的屏蔽词转换成* import re #参数为路径,返回整个屏蔽词文本 def get_f(path): f = open(path,'r',encoding='utf-8') art=f.read() f.close() return art #参数为字符串,返回一个屏蔽词列表 def get_list(str): list_=[] word = re.findall(r'[^\s]+',str) for i in word: list_.append(i.lower()) return list_ #参数i为输入,b为屏蔽词列表 def pri(i,b): ww=[] ww.append(i) h=0 for n in b: if re.findall(n,ww[h]) != []: s='*'*len(n) p = re.sub(n,s,ww[h]) h+=1 ww.append(p) if h != 0: #print('共替换了%d个词'%h) return ww[h] else: return i #run if __name__ == "__main__": path=r'E:\vscode\code\ban.txt' b=get_list(get_f(path)) #print(b) i=str(input('输入:\n')) print(pri(i,b))
#生成自定义数量由大小写字母与数字随机组成的号码/激活码,然后存入mysql数据库 import random import string import MySQLdb #获取号码 def GenKey(length): #length为号码长度 chars = string.ascii_letters + string.digits #string.ascii.letters是26个英文字母的大小写[a-z A-Z],string.digits为[0-9]相加作为字典 return ''.join([random.choice(chars) for i in range(length)]) #拿出chars内的一个字符并重复进行length次,将得到的字符与空字符串相加,得到长度为length的号码 #保存号码 def SaveKey(content): f = open('Result Key.txt', 'a') #打开Result Key.txt,a表示“打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。” f.write(content) #写入一个content,此处为号码 f.write('\n') #换行 f.close() #关闭 #保存至mysql数据库 def save_sql(code_nu): host = ("localhost") user = ("root") pass_ = ("123456") db = ("sqlforpy") #建立连接 connect = MySQLdb.connect(host,user,pass_,db) #使用cursor()方法获取操作游标 (在操作游标中才可进行数据库操作 cursor = connect.cursor() #使用insert into进行插入数据 sql = "insert into code(code)VALUES('%s')" % code_nu #执行sql语句 cursor.execute(sql) #使用commit提交到数据库执行保存 connect.commit() #关闭连接 connect.close() if __name__ == '__main__': length=int(input("\n请输入需要的号码个数:")) for i in range(length): value = GenKey(20) print (value) #SaveKey(value) save_sql(value)
#读取一个纯英文的文本文件,统计其中每个单词的出现次数,并将次数和其单词本身存入mysql数据库 import re import MySQLdb #读取文件信息 filename="word.txt" #使用open方法操作文本文件,r表示以只读方式打开文件。文件的指针将会放在文件的开头 f=open(filename,'r') #使用f.read方法返回整个文本文件给article, artical=f.read() #使用f.close关闭文件 f.close() #将文本中的所有英文单词筛选出来 去掉标点和其他文本符号 并且将单词都小写保存在数组List中 List=[] #'[a-zA-Z]+'正则表达式,表示大小写a-z出现一次或连续出现,这里表达一个单词 #使用re.findall方法,从article中获取单词,作为list存入word中 word=re.findall('[a-zA-Z]+',artical) for i in word: List.append(i.lower()) #把单词与出现的次数存入数据库(我也不知道为什么要存进去:) def save_sql(word,numbers): host = ("localhost") user = ("root") pass_ = ("123456") db = ("sqlforpy") #建立连接 connect = MySQLdb.connect(host,user,pass_,db) #使用cursor()方法获取操作游标 (在操作游标中才可进行数据库操作 cursor = connect.cursor() #使用insert into进行插入数据 sql = "insert into count_word(word,numbers)VALUES('%s','%d')" % (word,numbers) #执行sql语句 try: cursor.execute(sql) #使用commit提交到数据库执行保存 connect.commit() except: #发生错误时回滚 connect.rollback() #关闭连接 connect.close() #统计单词数目 print("%s总共有%d个单词" %(filename,List.__len__())) #统计各个单词出现的频率,并且按照字典顺序输出并将内容写入文件中 #f=open("result.txt",'w') List=sorted(List) i=0 for i in range(0,List.__len__()-1): #使用count方法获得字符串出现的次数 count=List.count(List[i]) if(List[i]!=List[i+1]): #print(List[i]+" "+str(count)+"\n") #f.write(List[i]+" "+str(count)+"\n") save_sql(List[i],count)
#在一个文件夹内存放着几个纯英文文本,统计其中出现次数最多的单词 import os import re f_dir='E:/vscode/code/testwork/txtfile' f_list=os.listdir(f_dir) List=[] dict={} #传入文件名,返回文本文件路径 def get_f(name): return f_dir+'/'+name #传入文件路径,返回文件内文本(字符串 def open_f(fdir): f = open(fdir,'r',encoding='UTF-8') artical=f.read() f.close() return artical #传入字符串,找出其中的单词统一小写,并以list形式添加到List中 def get_w(file): word=re.findall('[a-zA-Z]+',file) for i in word: List.append(i.lower()) #传入一个list,将其排序后,提取每个单词与其出现的次数,以字典形式存放于dict def get_c(w_list): s_list=sorted(w_list) i = 0 for i in range(0,s_list.__len__()-1): count=s_list.count(s_list[i]) if(s_list[i]!=s_list[i+1]): dict[s_list[i]]=count if __name__ == "__main__": art='' for i in f_list: f_path=get_f(i) art=art+open_f(f_path) get_w(art) get_c(List) #用max方法找出字典内values最大的值 highest=max(dict.values()) print('所有文件共有%d个单词'%List.__len__()) print('出现最多次的单词:') #用最大值去提取与其相匹配的key,得到一个或多个出现次数最高的单词 print([k for k,v in dict.items() if v == highest]) print('总共出现了%d次'%highest)
#有一个文件夹内存放着代码文件,统计所有文件的代码行,注释行和空行的总数 import os def j_anno(line): if line.strip().startswith("#"): return True else: return False def j_annos(line): if line.strip().startswith("'''") or line.strip().startswith('"""'): return True else: return False path='E:/vscode/code/testwork' code_line=0 comm_line=0 space_line=0 for root,dirs,files in os.walk(path): for item in files: f_path=os.path.join(root,item) f_exten=os.path.splitext(f_path)[1] if f_exten == '.py': with open(f_path,'r',encoding='utf-8') as fp: #print('key:',key) #print('value:',value) while True: line=fp.readline() if not line: break elif j_anno(line): comm_line +=1 elif j_annos(line): while True: line=fp.readline() if j_annos(line): break else: comm_line +=1 elif line.strip(): code_line+=1 else: space_line+=1 #test print('目录:%s总共有:\n%d行代码\n%d行注释\n%d个空行'%(path,code_line,comm_line,space_line))
#加入随机salt的哈希运算验证 import random from hashlib import sha256 from hmac import HMAC #意义在于,随机halt哈希混淆运算后的数据极难被反推出密码原文,彩虹字典的暴力破解难度极大 #参数r_pass为密码原文,salt可选,返回一个带slat与加密后的字符串 def get_pass(r_pass,salt=None): if salt == None: salt=sha256(str(random.random()).encode('utf-8')).hexdigest()[-8:] #先生成一个HMAC()对象,然后再调用digest()生成hash之后的结果 password=HMAC(salt.encode('utf-8'),r_pass.encode('utf-8'),sha256).hexdigest() return ('%s$%s'%(salt,password)) #参数r_pass为再次输入的原文密码,password为第一次哈希后的字符串 def check_pass(r_pass,password): salt=password.split('$')[0] return password == get_pass(r_pass,salt) #run if __name__ == "__main__": password=input('请输入密码:\n') p=get_pass(password) while True: pass_=input('请再次输入密码:\n') if check_pass(pass_,p): print('密码正确') break else: print('密码错误')