图片等比例缩放实现

#设定一个分辨率,使一个文件夹内所有大于该分辨率的图像都进行等比例缩放 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)

2020-06-27 · 2 min · 509 words · kutake

实战:通话统计及简易图表制作

最开始的看到的python基础习题之一,现在顺便扩展一点,练习xlrd、pandas以及matplotlib的练习 数据来源 来自于联通官网的通话数据下载,文件为某年某月的通话记录详情,格式为xls**[图片缺失: 2020/06/QQ截图20200627215145.png]** ...

2020-06-27 · 7 min · 3313 words · kutake

文本识别屏蔽词转换

#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))

2020-06-27 · 1 min · 197 words · kutake

随机码生成

#生成自定义数量由大小写字母与数字随机组成的号码/激活码,然后存入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)

2020-06-26 · 1 min · 484 words · kutake

统计英文单词词频

#读取一个纯英文的文本文件,统计其中每个单词的出现次数,并将次数和其单词本身存入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)

2020-06-24 · 2 min · 557 words · kutake

统计文件夹内所有文件的词频

#在一个文件夹内存放着几个纯英文文本,统计其中出现次数最多的单词 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)

2020-06-23 · 1 min · 366 words · kutake

统计文件夹内所有代码文件的代码行、注释行和空行

#有一个文件夹内存放着代码文件,统计所有文件的代码行,注释行和空行的总数 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))

2020-06-22 · 1 min · 195 words · kutake

哈希加密验证尝试

#加入随机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('密码错误')

2020-06-21 · 1 min · 327 words · kutake

未读消息图标模拟

from PIL import Image,ImageFont,ImageDraw import sys reload(sys) #必须要reload sys.setdefaultencoding('utf-8') #字符编码改为utf8 headPath=r"" #头像图片路径 output=r"" #处理后输出路径 fontPath=r"" #字体路径 headFile="" #头像文件 outFile="" #输出文件 #打开图片建立画布 image=Image.open(headPath+headFile,r) draw=ImageDraw.Draw(image) #由图片大小确定字体大小 fontsize=min(image.size)/4 #增加文字 fontobj=ImageFont.truetype(font=fontPath+"AdobeHeisistd-Regular.otf",size=fontsize,index=0,encoding=",filename=None)# """ """ from PIL import Image,ImageFont,ImageDraw#从PIL库导入所需模块 import sys reload(sys) #必须要reload sys.setdefaultencoding('utf-8')#字符编码改为utf8 headPath=r"E:\\vscode\\code\\testwork\\testFile\\" #头像图片路径 outputPath=r"C:E:\\vscode\\code\\testwork\\testFile\\output\\" #处理后输出路径 fontPath=r"C:\\Windows\\Fonts\\" #字体路径 headFile="head.jpg" #头像文件 outFile="output.jpg" #输出文件 #打开图片,建立画布 image=Image.open(headPath+headFile,'r') draw=ImageDraw.Draw(image) #由图片大小确定字体大小 fontsize=min(image.size)/4 #增加文字 fontobj=ImageFont.truetype(font=fontPath+"AdobeHeitiStd-Regular.otf",size=fontsize,index=0,encoding='',filename=None)#实例字体对象 draw.text((image.size[0]-fontsize,0),text="5",fill=(255,0,0),font=fontobj,anchor=None)#用draw对象的text()方法添加文字 image.save(outputPath+outFile)#保存图片 """ #!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2016/12/12 上午10:13 # @Author : hukezhu # @Site : # @File : 0000:添加未读消息.py # @Software: PyCharm from PIL import Image, ImageDraw, ImageFont #创建图片对象 headImage = Image.open('E:/vscode/code/testwork/testFile/head.jpg') #获取图片对象的宽高 w,h = headImage.size #创建字体对象 font = ImageFont.truetype('C:/Windows/Fonts/Arial.ttf',int(h/4)) #绘制圆形 ImageDraw.Draw(headImage).pieslice([(w/3*2,0),(w,h/3)],0,360,fill='red') ImageDraw.Draw(headImage).text((w*0.76,h*0.02),'3',font = font, fill = 'white') #展示绘制结果(使用系统默认的图片浏览器) #headImage.show() #保存绘制结果 headImage.save('E:/vscode/code/testwork/testFile/wode.jpg')

2020-05-29 · 2 min · 681 words · kutake