效果:
点表情图,在表单中表示为[左晃晃]。
见过一个使用jquery来模拟新浪微博的表情插入。
使用Python2.7和Django1.6来实现。
看书好长时间,但是自己来写,发现真的没记住。
方法描述:
1、浏览器页面,使用js脚本把表情符号添加到Textarea;
2、Views里面使用正则把记录里的[]内容替换为图片,渲染到浏览器。
使用一个简单的Sqlite3数据表。
settings.py里设置sqlite3很简单,默认就好。
由于编码问题,项目使用英文路径,创建数据库不会出现问题。
models.py
class emotion(models.Model):
text=models.CharField(max_length=100)
默认一个ID自动增长字段。
views.py
#coding:utf-8
#使用python 2.7.6 django 1.6实现
import re
from django.shortcuts import render,render_to_response
dels import emotion
#define emotion picture
emotion_category=[u'正常']
emotion_pictures={u'[左晃晃]':u'images/zhh_thumb.gif',u'[右晃晃]':u'images/yhh_thumb.gif'}
#display form
def emotion_form(request):
'''显示表情表单'''
emotion_1 = emotion()
#从表单取数据,存入数据表emotion
hod == 'POST':
= ('text','')
emotion_1.save()
#取所有记录
query = emotion.objects.all()
return render_to_response('emotion.html',{'emotion_category':emotion_category,'emotion_pictures':emotion_pictures, 'query':query})
只实现记录的保存,并渲染记录。
csrf这个直接注释掉了,没使用。
网页部分只列js代码,就2句:
{% for alt,url in emotion_pictures.items %}
{% endfor %}
function addText(event,id) {
}
static指令失效,也是由于编码问题,要修改python的site.py把编码直接改到gbk。
这里使用了js的event事件。
显示记录,使用过滤器来把[]转换为图片。
{% for q in query %}
{{ q.text|emotion_replace|safe }}
{% endfor %}
使用safe,避免html标签被自动转义。
emotion_replace 是自定义过滤器。
#coding:utf-8
import re
from django import template
from form1 import settings
#定义过滤器,替换文字为图像
#中文范围 : [u4e00-u9fa5]
register=template.Library()
#使用全局变量
emotion_pictures={u'[左晃晃]':'images/zhh_thumb.gif',u'[右晃晃]':'images/yhh_thumb.gif'}
#@register.filter
def emotion_replace(value):
pattern = repile(ur'([[u4e00-u9fa5]+])')
#使用findall取得所有匹配结果
match = re.findall(pattern,value)
if match is not None:
#循环结果列表
for g in match:
#[左晃晃]如果在字典中存在
if (g, '') != '':
pic = ''
#使用replace方法替换
value = place(g, pic)
return value
register.filter(emotion_replace)
过滤器在一个文件中定义,放到文件夹中,和templates同级,叫templatetags。
emotion_replace.py
#coding:utf-8
import re
from django import template
from form1 import settings
#定义过滤器,替换文字为图像
#中文范围 : [u4e00-u9fa5]
register=template.Library()
#使用全局变量
emotion_pictures={u'[左晃晃]':'images/zhh_thumb.gif',u'[右晃晃]':'images/yhh_thumb.gif'}
#@register.filter
def emotion_replace(value):
pattern = repile(ur'([[u4e00-u9fa5]+])')
#使用findall取得所有匹配结果
match = re.findall(pattern,value)
if match is not None:
#循环结果列表
for g in match:
#[左晃晃]如果在字典中存在
if (g, '') != '':
pic = ''
#使用replace方法替换
value = place(g, pic)
return value
register.filter(emotion_replace)
最重要的是pattern = repile(ur‘([[u4e00-u9fa5]+])‘)这句。匹配[左晃晃]。
[ ] 表示转义,匹配[]
[u4e00-u9fa5]匹配任意Unicode字符
+匹配多个字符,要避免贪婪,可以加一个?()
把[..]匹配的返回为一个group使用findall方法,返回一个列表,不使用groups方法。使用replace方法,而不是用re去替换,简化了问题。
Python 2.7的编码问题真麻烦。
ur的顺序不能颠倒,表示unicode和raw字符串。
看起来,比jquery的实现,代码要少很多。这里也没做autotest。程序很简单,好不容易写出表情替换和显示。
原文:
本文发布于:2024-02-01 06:54:19,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170674166134698.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |