知道这个功能是从聚能聊话题“2018程序员拜年的奇思妙想,涨姿势了”
操作起来很方便,这里将个人尝试遇到的问题记录一下。
题主用的是python3,代码在 python 2.7 下还需要改一改。
import sys
defaultencoding = 'utf-8'
if sys.getdefaultencoding() != defaultencoding:
reload(sys)
sys.setdefaultencoding(defaultencoding)
import itchat,time,re
from itchat.content import *
@itchat.msg_register([TEXT])
def text_reply(msg):
print(msg['Text'])
match = re.search(u'[\u5e74]',msg['Text'])
print(match)
if match:
itchat.send(('那我就祝您狗年大吉大利'), msg['FromUserName'])
@itchat.msg_register([PICTURE, RECORDING, VIDEO, SHARING])
def other_reply(msg):
itchat.send(('那我就祝您狗年大吉大利'), msg['FromUserName'])
itchat.auto_login(enableCmdQR=True,hotReload=True)
itchat.run()
我的环境:Win7+python 2.7,默认编码估计是GBk;
文件以 UTF-8 编码保存,还是遇到编码问题。
所以文件开头添加了设置默认编码的方法;
另外正则表达式中不支持直接使用中文字符,而是需要转换为 u5e74 的形式。
轮换方法,cmd 下执行 python 进入 python 命令提示符模式
执行:
>>> u'中文'.encode('unicode_escape')
输出为:
'\\u4e2d\\u6587'