python中執行mysql遇到like 怎麼辦 ?
sql = "SELECT * FROM T_ARTICLE WHERE title LIKE '%%%%%s%%%%'" % searchStr
執行成功,print出SQL語句之後爲:
SELECT * FROM T_ARTICLE WHERE title LIKE '%%生活%%'
原因:
Python在執行sql語句的時候,同樣也會有%格式化的問題,仍然需要使用%%來代替%。因此要保證在執行sql語句的時候格式化正確。而不只是在sql語句(字符串)的時候正確。
import Image, ImageDraw, ImageFont, ImageFilter
import random
隨機字母
def rndChar():
return chr(random.randint(65, 90))
隨機顏色1
def rndColor():
return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))
隨機顏色2
def rndColor2():
return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))
240 * 60
width = 60 * 4
height = 60
image = Image.new('RGB', (width, height), (255,255,255))
創建Font對象
font = ImageFont.truetype('/usr/share/fonts-droid/truetype/DroidSansFallback.ttf', 36)
創建Draw對象
draw = ImageDraw.Draw(image)
填充每個像素
for x in range(width):
for y in range(height):
draw.point((x, y),fill=rndColor())
輸出文字
for t in range(4):
draw.text((60 * t +10, 10), rndChar(), font=font, fill=rndColor2())
模糊
image = image.filter(ImageFilter.BLUR)
image.save('/home/godben/code.jpg', 'jpeg')
#!/usr/bin/env python
#coding=utf-8
import random
from PIL import Image, ImageDraw, ImageFont, ImageFilter
_letter_cases = "abcdefghjkmnpqrstuvwxy" # 小寫字母,去除可能干擾的i,l,o,z
_upper_cases = _letter_cases.upper() # 大寫字母
_numbers = ''.join(map(str, range(3, 10))) # 數字
init_chars = ''.join((_letter_cases, _upper_cases, _numbers))
def create_validate_code(size=(120, 30),
chars=init_chars,
img_type="GIF",
mode="RGB",
bg_color=(255, 255, 255),
fg_color=(0, 0, 255),
font_size=18,
font_type="kk.TTF",
length=4,
draw_lines=True,
n_line=(1, 2),
draw_points=True,
point_chance = 2):
'''
@todo: 生成驗證碼圖片
@param size: 圖片的大小,格式(寬,高),默認爲(120, 30)
@param chars: 允許的字符集合,格式字符串
@param img_type: 圖片保存的格式,默認爲GIF,可選的爲GIF,JPEG,TIFF,PNG
@param mode: 圖片模式,默認爲RGB
@param bg_color: 背景顏色,默認爲白色
@param fg_color: 前景色,驗證碼字符顏色,默認爲藍色#0000FF
@param font_size: 驗證碼字體大小
@param font_type: 驗證碼字體,默認爲 ae_AlArabiya.ttf
@param length: 驗證碼字符個數
@param draw_lines: 是否劃干擾線
@param n_lines: 干擾線的條數範圍,格式元組,默認爲(1, 2),只有draw_lines爲True時有效
@param draw_points: 是否畫干擾點
@param point_chance: 干擾點出現的概率,大小範圍[0, 100]
@return: [0]: PIL Image實例
@return: [1]: 驗證碼圖片中的字符串
'''
width, height = size # 寬, 高
img = Image.new(mode, size, bg_color) # 創建圖形
draw = ImageDraw.Draw(img) # 創建畫筆
def get_chars():
'''生成給定長度的字符串,返回列表格式'''
return random.sample(chars, length)
def create_lines():
'''繪製干擾線'''
line_num = random.randint(*n_line) # 干擾線條數
for i in range(line_num):
# 起始點
begin = (random.randint(0, size[0]), random.randint(0, size[1]))
#結束點
end = (random.randint(0, size[0]), random.randint(0, size[1]))
draw.line([begin, end], fill=(0, 0, 0))
def create_points():
'''繪製干擾點'''
chance = min(100, max(0, int(point_chance))) # 大小限制在[0, 100]
for w in xrange(width):
for h in xrange(height):
tmp = random.randint(0, 100)
if tmp > 100 - chance:
draw.point((w, h), fill=(0, 0, 0))
def create_strs():
'''繪製驗證碼字符'''
c_chars = get_chars()
strs = ' %s ' % ' '.join(c_chars) # 每個字符前後以空格隔開
font = ImageFont.truetype(font_type, font_size)
font_width, font_height = font.getsize(strs)
draw.text(((width - font_width) / 3, (height - font_height) / 3),
strs, font=font, fill=fg_color)
return ''.join(c_chars)
if draw_lines:
create_lines()
if draw_points:
create_points()
strs = create_strs()
# 圖形扭曲參數
params = [1 - float(random.randint(1, 2)) / 100,
0,
0,
0,
1 - float(random.randint(1, 10)) / 100,
float(random.randint(1, 2)) / 500,
0.001,
float(random.randint(1, 2)) / 500
]
img = img.transform(size, Image.PERSPECTIVE, params) # 創建扭曲
img = img.filter(ImageFilter.EDGE_ENHANCE_MORE) # 濾鏡,邊界加強(閾值更大)
return img, strs
if name == "main":
code_img = create_validate_code()
code_img[0].save("xiaorui.cc.gif", "GIF")
#coding:utf-8
#編寫驗證碼
#隨機的數值
#圖片
import random #python隨機模塊
from PIL import Image #圖片
from PIL import ImageDraw #畫筆
from PIL import ImageFont #字體
from PIL import ImageFilter #濾鏡 驗證碼扭曲
#驗證碼編寫步驟
#1、定義隨機數
sample_text = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
sample_list = random.sample(sample_text,4)
randomText = "".join(sample_list)
#2、定義圖片
img = Image.new("RGB",(150,50),(255,255,255))
#第一個參數是配色方案
#第二個參數是圖片的尺寸px 寬高
#第三個參數是顏色 255,255,255是白色
#3、圖片上繪製干擾項
#實例化畫筆
draw = ImageDraw.Draw(img)
#繪製干擾線
for i in range(random.randint(10,20)): #隨機循環1-10次
draw.line(
#兩個點決定一條線
#每個點有x,y兩個值
[
(
random.randint(1,150), # x
random.randint(1,150), # y
),#點一
(
random.randint(1,150), # x
random.randint(1,150), # y
)#點二
],#一條線
fill = (random.randint(0,255),random.randint(0,255),random.randint(0,255)) #線條顏色
) #繪製線條
#繪製點
for j in range(1000):
draw.point(
[ random.randint(1, 150), # x
random.randint(1, 150), # y
],#一個點
fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) # 線條顏色
)
#4、書寫文字
#定義字體
text = "".join(randomText)
font = ImageFont.truetype("simsun.ttc",36) #定義字體
draw.text((random.randint(1, 10),random.randint(1, 5)),text,font = font,fill = "green") #書寫文字
#文字起始位置
#文字內容
#文字字體
#文字顏色
#5、進行濾鏡扭曲
#定義扭曲的參數
params = [
1-float(random.randint(1,2))/100,
0,
0,
0,
1 - float(random.randint(1, 2)) / 100,
float(random.randint(1, 2)) / 100,
0.001,
float(random.randint(1, 2)) / 100
]
#使用濾鏡
img = img.transform((150,50),Image.PERSPECTIVE,params)
img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)
#6、查看效果
img.show() #展示
img.save("%s.jpg"%randomText,"JPEG") #保存,保存路徑
生成隨機驗證碼圖片
import string
from random import randint, sample
from PIL import Image, ImageDraw, ImageFont, ImageFilter
Image 負責處理圖片
ImageDraw 畫筆
ImageFont 文字
ImageFileter 濾鏡
定義變量
img_size = (150,50) # 定義畫布大小
img_rgb = (255,255,255) # 定義畫布顏色,白色
img = Image.new("RGB",img_size,img_rgb)
img_text = " ".join(sample(string.ascii_letters+string.digits, 5))
print(img_text.replace(' ',''))
畫圖
drow = ImageDraw.Draw(img)
for i in range(10):
隨機畫線
drow.line([tuple(sample(range(img_size[0]),2)), tuple(sample(range(img_size[0]),2))], fill=(0,0,0))
for i in range(99):
隨機畫點
drow.point(tuple(sample(range(img_size[0]),2)), fill=(0,0,0))
文字
font = ImageFont.truetype("simsun.ttc", 24) # 定義文字字體和大小
drow.text((6,6), img_text, font=font, fill="green")
扭曲圖片和濾鏡
params = [
1 - float(randint(1,2)) / 100,
0,
0,
0,
1 - float(randint(1,10)) /100,
float(randint(1,2)) / 500,
0.001,
float(randint(1,2)) / 500
]
img = img.transform(img_size, Image.PERSPECTIVE, params)
img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)
展示圖片
img.show()
寫一個理財計算器,實現將每日/月/年的利息進行復投進行計算
money = float(input('請輸入您打算用來投資的本金 \> '))
year = int(input('請輸入投資期限(單位:年) \> '))
rate = float(input('請輸入投資年化收益率 \> '))
Type = int(input('''1.每日利息復投 2.每月利息復投 3.每年利息復投 請選擇復投方式 \> '''))
def day_return(money,year,rate=0.12):
'方案:每日利息加入本金復投!'
for y in range(year):
for day in range(365):
money = money*rate/365 + money
print('第%d年結束時,本金爲:%.2f' % (y+1,money))
def month_return(money,year,rate=0.12):
'方案:每月利息加入本金復投!'
for y in range(year):
for month in range(12):
money = money*rate/12 + money
print('第%d年結束時,本金爲:%.2f' % (y+1,money))
def year_return(money,year,rate=0.12):
'方案:每年利息加入本金復投!'
for y in range(year):
money = money*rate + money
print('第%d年結束時,本金爲:%.2f' % (y+1,money))
if Type == 1:
day_return(money,year,rate)
elif Type == 2:
month_return(money,year,rate)
elif Type == 3:
year_return(money,year,rate)
else:
print('輸入有誤!')
百度翻譯
Python 3.5.1
from urllib import request, parse
import json
url = 'http://fanyi.baidu.com/v2transapi'
context = input('請輸入需要翻譯的內容 :\> ')
if context >= '\u4e00' and context <= '\u9fa5':
判斷輸入內容是否爲漢字
From,To = 'zh','en'
else:
From,To = 'en','zh'
data = {
'query':context,
'from':From,
'to':To,
'transtype':'translang',
'simple_means_flag':3
}
data = parse.urlencode(data).encode('utf-8')
r = request.Request(url,data)
r.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0')
html = request.urlopen(r).read().decode('utf-8')
Result = json.loads(html)
print('翻譯結果爲:' + Result['trans_result']['data'][0]['dst'])
簡單的拼手氣紅包
import random
from time import sleep
所有涉及金額的浮點數都需要用 round 方法保留2位小數,避免出現最終結果多出0.01
amount = round(float(input('請設置紅包的金額 \> ')),2)
num = int(input('請設置紅包的數量 \> '))
hb_dict = {}
xing = '趙錢孫李周吳鄭王'
ming = '一二三四五六七八九十'
while num:
xingming = random.choice(xing)+random.choice(ming)+random.choice(ming)
if xingming in hb_dict.keys():
xingming = random.choice(xing)+random.choice(ming)+random.choice(ming)
num -= 1
if num == 0:
print('%s搶到紅包%.2f元 紅包搶完了!' % (xingming,amount))
hb_dict[amount] = xingming
amount -= amount
elif num > 0:
hb = round(random.uniform(0.01,amount)/num,2)
hb_dict[hb] = xingming
# 算法: 在0.01到紅包總金額之間隨機一個浮點數 / 紅包剩餘個數
print('%s搶到紅包%.2f元 剩餘%d個!' % (xingming,hb,num))
amount = round((amount - hb),2)
sleep(1)
轉置字典中的 key / value
hb_dict2 = {value:key for key,value in hb_dict.items()}
max_hb = max(hb_dict.items())
print('%s運氣最佳 搶得%.2f元!!' % (max_hb[1],max_hb[0]))
隨機生成200個序列號
import random
import string
for num in range(200):
numlist = []
for i in range(12):
numlist.append(random.choice(string.ascii_uppercase+string.digits))
print(''.join(numlist))
with open('200.txt', 'a') as f: # 'a' 表示追加寫入
f.write(''.join(numlist)+'\n')
f.close
import Image, ImageFont, ImageDraw
text = "EwWIieAT"
im = Image.new("RGB",(130,35), (255, 255, 255))
dr = ImageDraw.Draw(im)
font = ImageFont.truetype("kk.TTF", 24)
#simsunb.ttf 這個從windows fonts copy一個過來
dr.text((10, 5), text, font=font, fill="#000000")
im.show()
im.save("t.png")
縮略圖
from PIL import Image
img = Image.open('god.jpg')
img = img.resize((250, 156), Image.ANTIALIAS)
img.save('sharejs_small.jpg')
PythonWare公司提供了免費的圖像處理工具包PIL(Python Image Library),該軟件包提供了基本的圖像處理功能,本文介紹了使用PIL工具包中的Image模塊進行比對的過程。
#!/usr/bin/env python
-- coding:utf-8 --
import Image, ImageChops
img1 = Image.open(r'C:\cygwin\tmp\Sonic1.jpg') Capture1.PNG
img2 = Image.open(r'C:\cygwin\tmp\Sonic2.jpg') Diff.jpg
img3 = ImageChops.invert(img2)
Image.blend(img1,img3,0.5).show()
PIL處理圖片之加水印
#!/usr/bin/env python
-- coding: utf-8 --
import Image, ImageEnhance, ImageDraw, ImageFont
def text2img(text, font_color="Blue", font_size=25):
"""生成內容爲 TEXT 的水印"""
font = ImageFont.truetype('simsun.ttc', font_size)
#多行文字處理
text = text.split('\n')
mark_width = 0
for i in range(len(text)):
(width, height) = font.getsize(text[i])
if mark_width < width:
mark_width = width
mark_height = height * len(text)
#生成水印圖片
mark = Image.new('RGBA', (mark_width,mark_height))
draw = ImageDraw.ImageDraw(mark, "RGBA")
draw.setfont(font)
for i in range(len(text)):
(width, height) = font.getsize(text[i])
draw.text((0, i*height), text[i], fill=font_color)
return mark
def set_opacity(im, opacity):
"""設置透明度"""
assert opacity >=0 and opacity < 1
if im.mode != "RGBA":
im = im.convert('RGBA')
else:
im = im.copy()
alpha = im.split()[3]
alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
im.putalpha(alpha)
return im
def watermark(im, mark, position, opacity=1):
"""添加水印"""
try:
if opacity < 1:
mark = set_opacity(mark, opacity)
if im.mode != 'RGBA':
im = im.convert('RGBA')
if im.size[0] < mark.size[0] or im.size[1] < mark.size[1]:
print "The mark image size is larger size than original image file."
return False
#設置水印位置
if position == 'left_top':
x = 0
y = 0
elif position == 'left_bottom':
x = 0
y = im.size[1] - mark.size[1]
elif position == 'right_top':
x = im.size[0] - mark.size[0]
y = 0
elif position == 'right_bottom':
x = im.size[0] - mark.size[0]
y = im.size[1] - mark.size[1]
else:
x = (im.size[0] - mark.size[0]) / 2
y = (im.size[1] - mark.size[1]) / 2
layer =Image.new('RGBA', im.size,)
layer.paste(mark,(x,y))
returnImage.composite(layer, im, layer)
exceptExceptionas
e:print">>>>>>>>>>> WaterMark EXCEPTION: "+ str(e)
returnFalsedef
main():
text = u'Linsir.水印.\[email protected]'#
text = open('README.md').read().decode('utf-8')#
print text
im =Image.open('origal.png')
mark = text2img(text)
image = watermark(im, mark,'center',0.9)
if image:
image.save('watermark.png')
image.show()else:print"Sorry, Failed."
if name =='main':
import sys, Image
img = Image.open(sys.argv[1]).convert('YCbCr')
w, h = img.size
data = img.getdata()
cnt = 0
for i, ycbcr in enumerate(data):
y, cb, cr = ycbcr
if 86 <= cb <= 117 and 140 <= cr <= 168:
cnt += 1
print '%s %s a porn image.'%(sys.argv[1], 'is' if cnt > w h 0.3 else 'is not')
運行:
E:/>c:/python25/python test_skin.py 114.jpeg
114.jpeg is a porn image.
import pymysql
獲取一個數據庫連接,注意如果是UTF-8類型的,需要制定數據庫
db=pymysql.connect(host="127.0.0.1",user="root",passwd="123456",db="mysql",charset='utf8' )
使用 cursor()方法創建一個遊標對象 cursor
cursor = db.cursor()
使用 execute()方法執行 SQL 查詢
cursor.execute("SELECT user,host,password from user")
使用 fetchall()方法獲取所有行.
data = cursor.fetchall()
print(data)
cursor.close()#關閉遊標
db.close()#關閉數據庫連接
import pymysql
db = pymysql.connect(host='10.3.1.174',user='root',password='123456',db='test')
cursor = db.cursor()
SQL 插入數據
sql = "INSERT INTO employee (first_name, last_name, age, sex, income) " \
"VALUES ('w', 'Eason', '29', 'M', '8000')"
SQL 更新數據
sql = "UPDATE employee first_name = Wang WHERE first_name = w"
SQL 刪除數據
sql = "DELETE FROM employee WHERE age > 20"
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()