前言
此次学flask框架是因为在csdn上看到了一个生成春联的文章(文章链接),感觉挺有意思的,自己的目的是把他做成小程序 理想功能:可以通过爬虫爬取某个网站上的对联文字,再通过python自动生成一副对联展示出来 每个用户点击小程序进去出现的对联都是随机的 每个用户可以自定义生成自己的对联
该小程序纯是写来自己玩,如果侵权了,我会及时删除
一、数据库配置文件
import pymysql
con = pymysql.connect(host='localhost', user='root', passwd='root', database='database', port=3306)
cur = con.cursor()
def sqlInsertFun(upSpring, downSpring, acrossSpring):
"""
:param upSpring:
:param downSpring:
:param acrossSpring:
:return:
"""
sqlInsert = 'insert into springText(springUp,springDown,springAcross) VALUES(%s,%s,%s)'
try:
cur.execute(sqlInsert, (upSpring, downSpring, acrossSpring))
con.commit()
print('插入成功')
return '200'
except Exception as erro:
print(erro)
con.rollback()
print('执行错误')
return erro
def sqlSelectFun():
"""
:return: 数据库随机的一条数据
"""
sqlSelect = 'SELECT * FROM springText as t1 WHERE t1.id>=(RAND()*(SELECT MAX(id) FROM springText))LIMIT 1;'
try:
cur.execute(sqlSelect)
springs = cur.fetchall()
for spring in springs:
springId = spring[0]
springUp = spring[1]
springDown = spring[2]
springAcross = spring[3]
return springId, springUp, springDown, springAcross
except Exception as erro:
print(erro)
print('查询错误')
return erro
二、爬取数据
写个爬虫,从网页上爬取数据,放到mysql数据库中
"""
1.先爬数据
2.筛选数据
3.把数据存到json文件中做测试
4.将数据导入到数据库
"""
import sqlConfig
import requests
import re
from lxml import etree
import random
def func():
url = 'http://www.360doc.com/content/16/0921/22/9570732_592642181.shtml'
resp = requests.get(url)
resp_html = etree.HTML(resp.text)
springText = resp_html.xpath('//*[@id="artContent"]/p/text()')
season_list = springText[1:]
for season in season_list:
result = re.sub(r'\d', "", season)
result1 = result[1:]
res = result1.split(';')
springUp = res[0]
springDown = res[1]
across_list = ['虎虎生威', '瑞虎迎新', '如虎添翼', '虎年大吉']
springAcross = across_list[random.randint(0, len(across_list)-1)]
sqlConfig.sqlInsertFun(springUp, springDown, springAcross)
func()
三、制作春联
import io
from PIL import Image
import requests
import sqlConfig
def get_word(ch, quality):
"""获取单个汉字(字符)的图片
ch - 单个汉字或英文字母(仅支持大写)
quality - 单字分辨率,H-640像素,M-480像素,L-320像素
"""
fp = io.BytesIO(requests.post(url='http://xufive.sdysit.com/tk', data={'ch': ch}).content)
im = Image.open(fp)
w, h = im.size
if quality == 'M':
w, h = int(w * 0.75), int(0.75 * h)
elif quality == 'L':
w, h = int(w * 0.5), int(0.5 * h)
return im.resize((w, h))
def get_bg(quality):
"""获取春联背景的图片"""
return get_word('bg', quality)
def write_couplets(text, HorV='V', quality='L', out_file=None):
"""生成春联
text - 春联内容,以空格断行
HorV - H-横排,V-竖排
quality - 单字分辨率,H-640像素,M-480像素,L-320像素
out_file - 输出文件名
"""
usize = {'H': (640, 23), 'M': (480, 18), 'L': (320, 12)}
bg_im = get_bg(quality)
text_list = [list(item) for item in text.split()]
rows = len(text_list)
cols = max([len(item) for item in text_list])
if HorV == 'V':
ow, oh = 40 + rows * usize[quality][0] + (rows - 1) * 10, 40 + cols * usize[quality][0]
else:
ow, oh = 40 + cols * usize[quality][0], 40 + rows * usize[quality][0] + (rows - 1) * 10
out_im = Image.new('RGBA', (ow, oh), '#f0f0f0')
for row in range(rows):
if HorV == 'V':
row_im = Image.new('RGBA', (usize[quality][0], cols * usize[quality][0]), 'white')
offset = (ow - (usize[quality][0] + 10) * (row + 1) - 10, 20)
else:
row_im = Image.new('RGBA', (cols * usize[quality][0], usize[quality][0]), 'white')
offset = (20, 20 + (usize[quality][0] + 10) * row)
for col, ch in enumerate(text_list[row]):
if HorV == 'V':
pos = (0, col * usize[quality][0])
else:
pos = (col * usize[quality][0], 0)
ch_im = get_word(ch, quality)
row_im.paste(bg_im, pos)
row_im.paste(ch_im, (pos[0] + usize[quality][1], pos[1] + usize[quality][1]), mask=ch_im)
out_im.paste(row_im, offset)
if out_file:
out_im.convert('RGB').save(out_file)
out_im.show()
spring = sqlConfig.sqlSelectFun()
text0 = spring[1]
text1 = spring[2]
text2 = spring[3]
write_couplets(text0, HorV='V', quality='M', out_file='上批.jpg')
write_couplets(text1, HorV='V', quality='M', out_file='下批.jpg')
write_couplets(text2, HorV='H', quality='M', out_file='横批.jpg')
四、效果图
|