Python習(xí)題和答案

習(xí)題地址:https://github.com/Yixiaohan/show-me-the-code


0、將你的 QQ 頭像(或者微博頭像)右上角加上紅色的數(shù)字,類似于微信未讀信息數(shù)量那種提示效果。 類似于圖中效果
# coding=utf-8
from PIL import Image, ImageDraw, ImageFont # Pillow

# 打開原圖片
openImg = Image.open('./etc/ac345982b2b7d0a2e416b6c2caef76094a369a96.jpg')
size = (0, 0, 125, 125)

# 新圖片
newImg = Image.new('RGB', openImg.size, (0, 0, 0))
draw = ImageDraw.Draw(newImg)

# 粘貼
newImg.paste(openImg.crop(size), # 復(fù)制
             size)               # 大小
draw.text((90, 2), # 坐標(biāo)
          '14',    # 字符串
          font = ImageFont.truetype('./etc/arial.ttf', 24), # 字體
          fill = (255, 0, 0))                               # 顏色
newImg.save('./etc/code1.png', 'png')
原圖片

新圖片

參考:
http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/00140767171357714f87a053a824ffd811d98a83b58ec13000
http://liam0205.me/2015/04/22/pil-tutorial-basic-usage/


1、做為 Apple Store App 獨(dú)立開發(fā)者,你要搞限時促銷,為你的應(yīng)用生成激活碼(或者優(yōu)惠券),使用 Python 如何生成 200 個激活碼(或者優(yōu)惠券)?
# coding=utf-8
import random
from PIL import Image, ImageDraw, ImageFont # Pillow

# 字符串相關(guān)
_String = 'Q W E R T Y U I O P A S D F G H J K L Z X C V B N M q w e r t y u i o p a s d f g h j k l z x c v b n m 1 2 3 4 5 6 7 8 9 0'.split(' ')
_Length = len(_String) - 1

# 生成隨機(jī)字符串(優(yōu)惠券id)
# @param {number} length: 字符串長度
# @return {string}: 返回字符串
def randomString(length = 0):
  s = ''
  i = 0
  while i < length:
    s += _String[random.randint(0, _Length)]
    i += 1
  return s

# 生成優(yōu)惠券
# @param {string} stringID: 優(yōu)惠券id
_Font = ImageFont.truetype('./etc/arial.ttf', 24)
def youHuiQuan(stringID):
  img = Image.new('RGB', (200, 40), (0, 0, 0))
  draw = ImageDraw.Draw(img)
  draw.text((5, 8), stringID, font = _Font, fill = (255, 255, 255))
  img.save('./result/' + stringID + '.jpg', 'jpeg')

# 初始化
def init():    
  i = 0   
  j = 5    
  while i < j:
    t = randomString(10)        
    youHuiQuan(t)        
    i += 1

init()

2、將 1 題生成的激活碼(或者優(yōu)惠券)保存到 MySQL關(guān)系型數(shù)據(jù)庫中。
# coding=utf-8
import random
import pymysql
from PIL import Image, ImageDraw, ImageFont # Pillow

# 字符串相關(guān)
_String = 'Q W E R T Y U I O P A S D F G H J K L Z X C V B N M q w e r t y u i o p a s d f g h j k l z x c v b n m 1 2 3 4 5 6 7 8 9 0'.split(' ')
_Length = len(_String) - 1

# 生成隨機(jī)字符串(優(yōu)惠券id)
# @param {number} length: 字符串長度
# @return {string}: 返回字符串
def randomString(length = 0):    
  s = ''    
  i = 0   
  while i < length: 
    s += _String[random.randint(0, _Length)]
    i += 1    
  return s

# 生成優(yōu)惠券
# @param {string} stringID: 優(yōu)惠券id
_Font = ImageFont.truetype('./etc/arial.ttf', 24)
def youHuiQuan(stringID):    
  img = Image.new('RGB', (200, 40), (0, 0, 0))    
  draw = ImageDraw.Draw(img)    
  draw.text((5, 8), stringID, font = _Font, fill = (255, 255, 255))    
  img.save('./result/' + stringID + '.jpg', 'jpeg')

# 存入數(shù)據(jù)庫
# @param db: 數(shù)據(jù)庫
# @param cursor: 數(shù)據(jù)庫游標(biāo)
# @param {string} rs: 隨機(jī)字符串
# @return {number}: 返回?cái)?shù)據(jù)庫是否有該字符串的結(jié)果
def sql(db, cursor, rs):    
  # 判斷數(shù)據(jù)庫是否有該字符串    
  sql1 = '''SELECT str FROM random              
            WHERE str = '%s' ''' % (rs)   
  r1 = cursor.execute(sql1)    
  # 如果r1 = 0,表示該字符串沒有生成過    
  if r1 == 0:        
    # 將字符串插入到數(shù)據(jù)庫中        
    sql2 = '''INSERT INTO random                  
              (str) 
              VALUES ('%s')''' % (rs)        
    r2 = cursor.execute(sql2)        
    db.commit()    
  return r1

# 初始化
'''
CREATE TABLE if not exists `random` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `str` varchar(255) DEFAULT NULL, 
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
'''
def init():    
  i = 0   
  j = 4    
  db = pymysql.connect('localhost', 'lianxi', 'lianxi', 'lianxi')   
  cursor = db.cursor()    
  # 循環(huán)    
  while i < j:        
    # 生成隨機(jī)字符串并將結(jié)果存入到數(shù)據(jù)庫        
    t = randomString(10)        
    n = sql(db, cursor, t)        
    # 返回0表示該隨機(jī)字符串沒有生成過,生成圖片并使i+1       
    if n == 0:            
      youHuiQuan(t)           
      i += 1    
    db.close()

init()

3、任一個英文的純文本文件,統(tǒng)計(jì)其中的單詞出現(xiàn)的個數(shù)。
# coding=utf8
import re

# 打開文件并讀取文本
file = open('./etc/t4.txt', 'r')
text = file.read()
file.close()

# 正則
regexp = re.compile(r'''[\s         # 匹配空格 
                        \n          # 匹配換行                        
                        .,!():'"?<> # 匹配特殊符號
                        ]+          # 匹配>=1個符合規(guī)則''', re.X)
newText = re.split(regexp, text)

# 統(tǒng)計(jì)每個單詞出現(xiàn)的個數(shù)
# -1是因?yàn)閿?shù)組的最后一位是''
wordLength = {}
for index in range(len(newText) - 1):    
  if newText[index] in wordLength:
    wordLength[newText[index]] += 1
  else:
    wordLength[newText[index]] = 1

# 輸出結(jié)果
print('A total of ' + str(len(newText) - 1) + ' words appeared.\n')
for key in wordLength:    
  print(key + ':' + str(wordLength[key]))

4、用 Python 寫一個爬圖片的程序,爬這個鏈接里的妹子圖片 :)
# coding=utf8
import re
import urllib
import urllib2

_TieBaURL = 'http://tieba.baidu.com/p/2166231880'

# get請求
def get(url):    
  request = urllib2.Request(url)   
  response = urllib2.urlopen(request)  
  return response.read()

# 獲取圖片字符串
def getImgUrl(html):
  h = re.compile(r'http://([^\s]+)\.(png|jpg)', re.I) 
  return h.findall(html)

# 下載
def download(urls):    
  txt = ''    
  for index in range(len(urls)):        
    t = urls[index][0] + '.' + urls[index][1]  # 文件地址
    u = 'http://' + t                          # http + 文件地址
    urllib.urlretrieve(u, './image/' + str(index) + '.' + urls[index][1])  # 下載并保存
    txt += u + '\n'    
  # 把地址存到文檔里    
  file = open('./image/url.txt', 'w+')    
  file.write(txt)    
  file.close()

# 初始化
def init():    
  html = get(_TieBaURL)  # 請求    
  urls = getImgUrl(html) # 分解獲得地址    
  download(urls)         # 下載

init()
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容