python小练习题
来源:互联网 发布:淘宝网运动鞋女款秋冬 编辑:程序博客网 时间:2024/05/19 04:06
0、在微信头像上添加未读信息数量提示效果
from PIL import Image ,ImageDraw, ImageFontQQim = Image.open('QQ.jpg')w,h=QQim.sizefont = ImageFont.truetype('/usr/share/wine/fonts/tahoma.ttf', int(h/4))ImageDraw.Draw(QQim).pieslice([(w/3*2, 0), (w, h/3)], 0, 360, fill="red")ImageDraw.Draw(QQim).text((w * 0.76, h * 0.02), '1', font=font, fill="white")QQim.show()QQim.save('QQimage.png')
1、做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券),使用 Python 如何生成 200 个激活码(或者优惠券)
import randomimport string'''field1 = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'\ 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'\ '0','1','2','3','4','5','6','7','8','9']'''field = string.letters + string.digitsdef getrandom(): return string.join(random.sample(field, 4)).replace(" ", "")def concatenate(group): for i in range(group): s = [] for i in range(4): s.append(getrandom()) print '-'.join(s)concatenate(10)
field一开始用的是field1的字典式,但生成的码偶尔会有五位的情况,后网上查了可以用string.letters + string.digits的形式,效果很好
2、将 0001 题生成的 200 个激活码(或者优惠券)保存到 MySQL 关系型数据库中。
前提条件:已经在root用户下建立了test数据库test表,列名为promotion,类型为text
import randomimport MySQLdbimport stringfield = string.letters + string.digitsdef getrandom(): return '-'.join(string.join(random.sample(field, 4)).replace(" ", "") for i in range(4))def AddToDatabase(group): try: conn = MySQLdb.connect(host='localhost', user='root', passwd='toor',db = 'test') cur = conn.cursor() for i in range(group): promotion = getrandom() cur.execute("insert into test values('%s')"%str(promotion)) except MySQLdb.Error, e: print "Mysql Error %d: %s" % (e.args[0], e.args[1]) conn.commit() cur.close() conn.close()AddToDatabase(200)
3、将 0001 题生成的 200 个激活码(或者优惠券)保存到 Redis 非关系型数据库中。
首先要将redis服务器打开:redis-server &
import randomimport redisimport stringfield = string.letters + string.digitsdef getrandom(): return '-'.join(string.join(random.sample(field, 4)).replace(" ", "") for i in range(4))def AddToDatabase(group): try: rc = redis.StrictRedis(host='127.0.0.1', port=6379, db=3) for i in range(group): promotion = getrandom() rc.set(i, str(promotion)) except Exception,e: print "Radis Error: %s" % str(e) rc.save() rc.shutdown()AddToDatabase(200)
4、任一个英文的纯文本文件,统计其中的单词出现的个数
import refn = open('Wuthering Heights.txt','r')dic_words= {}try: all_the_text = fn.read() all_the_text = all_the_text.lower() for line in all_the_text.split(): if line.isalpha(): if line not in dic_words: dic_words[line] = 1 else: dic_words[line] = dic_words[line]+1except Exception,e: print eprint dic_wordsfn.close()
5、你有一个目录,装了很多照片,把它们的尺寸变成都不大于 iPhone5 分辨率的大小
from __future__ import divisionimport Imageimport os,sysimport globimport reLenMaxSize = 1136WidthMaxSize = 640def JudgeImageSize(size): LenSize = max(size) WidSize = min(size) if LenSize > LenMaxSize or WidSize > WidthMaxSize: return (LenSize,WidSize) return (0,0)def ResizeImage(img,LenSize,WidSize): newing = [] reLenSize = 0 reWidSize = 0 if LenSize>0 and WidSize>0: if LenSize//LenMaxSize > WidSize//WidthMaxSize: reLenSize = LenMaxSize reWidSize = LenMaxSize*WidSize//LenSize else: reLenSize = WidthMaxSize*LenSize//WidSize reWidSize = WidthMaxSize print (LenSize,WidSize,reLenSize,reWidSize) newimg = img.resize((reLenSize, reWidSize), Image.ANTIALIAS) return newimgfor files in (glob.glob('chapter2/*.*')): #print files if re.findall('.jpg$',files) or re.findall('.png$',files)or re.findall('.bmp$',files): filename = os.path.basename(files) try: img = Image.open(files) except Exception, e: print e; (LenSize,WidSize) = JudgeImageSize(img.size) if (LenSize,WidSize) >(0,0): newimg=ResizeImage(img,LenSize,WidSize) newimg.save("chapter2/image/%s"%filename)
6、你有一个目录,放了你一个月的日记,都是 txt,为了避免分词的问题,假设内容都是英文,请统计出你认为每篇日记最重要的词
import os,sysimport globimport refor files in (glob.glob('*.txt')): #print files filename = os.path.basename(files) fn = open(filename,'r') dic_words= {} try: all_the_text = fn.read() all_the_text = all_the_text.lower() for line in all_the_text.split(): if line.isalpha(): if line not in dic_words: dic_words[line] = 1 else: dic_words[line] = dic_words[line]+1 except Exception,e: print e dic_sort = sorted(dic_words.iteritems(), key=lambda d:d[1],reverse =True) print 'In '+filename+',the most imporent word is :'+dic_sort[0][0] fn.close()
7、有个目录,里面是你自己写过的程序,统计一下你写过多少行代码。包括空行和注释,但是要分别列出来
和上个差不多,先空着
8、一个HTML文件,找出里面的正文。
# encoding=utf-8import urllib2import socketimport html2textfrom readability.readability import Documentsocket.setdefaulttimeout(4)url = 'http://news.ifeng.com/a/20160928/50038249_0.shtml'urlText = urllib2.urlopen(url)content = urlText.read()readable_article = Document(content).summary()readable_title = Document(content).short_title()print html2text.html2text(readable_article)
windows需要安装LXML模块,用pip install LXML安装出错的话,可以用以下方法:
(1)安装pip install wheel
(2)在这里下载对应的.whl文件:http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml
(3)进入.whl所在的文件夹,执行命令如:pip install lxml-3.6.4-cp27-cp27m-win32.whl
9、一个HTML文件,找出里面的链接。
#encoding:utf-8import socket,urllib2import htmllib,formatterurl = 'http://news.ifeng.com/a/20160928/50038249_0.shtml'urlText = urllib2.urlopen(url)content = urlText.read()parser=htmllib.HTMLParser(formatter.NullFormatter()) parser.feed(content)print '\n'.join(parser.anchorlist)parser.close()
10、使用 Python 生成类似于下图中的字母验证码图片
import Image,ImageDraw,ImageFontimport StringIO,sys,randomimport stringfield = string.letters + string.digitsLength = 120Width = 50def getrandom(): return string.join(random.sample(field, 1)).replace(" ", "")def gene_code(): verifi_code ='' newImg = Image.new("RGBA", (Length, Width), (255, 255, 255)) font = ImageFont.truetype('/usr/share/wine/fonts/tahoma.ttf',30) draw = ImageDraw.Draw(newImg) for i in range(4): verifi_code+=getrandom() verifi_code=' '.join(verifi_code) ImageDraw.Draw(newImg).text(((Length)*0.05, (Width)*0.25),verifi_code,font=font,fill="red") return newImgnewImg = gene_code()newImg.save("newImg.png","PNG")newImg.show()
13 : 用 Python 写一个爬图片的程序,爬这个链接里的日本妹子图片 :http://tieba.baidu.com/p/2166231880
from scrapy.spiders import Spiderfrom scrapy.selector import Selectorfrom airi_pic.items import AiriPicItemclass AiriPicSpider(Spider): name="airi_pic_spider" start_urls=[http://tieba.baidu.com/p/2166231880' ] def parse(self,response): sel=Selector(response) image_url=sel.xpath("//div[@id='post_content_29397251028']/img['BDG_Image']/@src").extract() print 'the urls:/n' print image_url print '/n' item=AiriPicItem() item['airi_image_url']=image_url yield item
21、 通常,登陆某个网站或者 APP,需要使用用户名和密码。密码是如何加密后存储起来的呢?请使用 Python 对密码加密。(看的网页的加密过程,不是自己写的,学习了)
import osfrom hashlib import sha256from hmac import HMACdef encrypt_password(password, salt=None): """Hash password on the fly.""" if salt is None: salt = os.urandom(8) # 64 bits. assert 8 == len(salt) assert isinstance(salt, str) if isinstance(password, unicode): password = password.encode('UTF-8') assert isinstance(password, str) result = password for i in xrange(10): result = HMAC(result, salt, sha256).digest() return salt + resulthashed = encrypt_password('secret password')
23、 使用 Python 的 Web 框架,做一个 Web 版本 留言簿 应用。
- python小练习题
- python初学过程的一些小练习题
- python 小练习题for初学者 part1
- Python练习题 9-6冰淇淋小店
- Python实战小程序——经典的python练习题
- Python 练习题
- python 练习题
- python 练习题
- python练习题
- Python练习题
- Python练习题
- Python练习题
- python练习题
- Python练习题
- Python练习题
- python练习题
- Python练习题
- python练习题
- http转https
- Android存储系统之架构篇
- 十进制到二进制的转换
- web前端-HTML段落-005
- 二维高斯模糊和可分离核形式的快速实现
- python小练习题
- 图像算法之三:特征提取算子之SIFT
- Button的上下图文混排
- COCOS2D-x封装物理引擎Phsics
- git使用
- ios10 plist 权限
- UILabel标签文字过长时的显示方式
- latex 字母上面加符号
- 程序的编译和链接问题