File message 应用
如果想写一个分析使用者传送的文章或是文件档的 Line bot,可以考虑使用 jieba 来帮助断词。
jieba 是一个可以帮助中文断词的套件,它有三种断词模式:精确模式,尝试将句子最精确地切开,适合文本分析;全模式,把句子中所有可以成词的词语都切割出来,但可能会有歧义;搜寻引擎模式,在精确模式的基础上,对长词再次切分,提高召回率,适合用于搜寻引擎分词。
断词时候所使用的停用字字典可以自行建立,也可以去网路上找已有的 txt 档来做使用或增减。
pip install
jieba
docx
範例程式码
import jieba.analyseimport docx@handler.add(MessageEvent)def handle_message(event): if event.message.type == 'file' try: UserSendFile = line_bot_api.get_message_content(event.message.id) # 存档案 path='./Files/' + UserId + '.docx' with open(path, 'wb') as fd: for chunk in UserSendFile.iter_content(): fd.write(chunk) # 读取文章 doc = docx.Document(path) words = "" for para in doc.paragraphs: words += para.text + '\n' # 删去停用字 for ch in stops: words = words.replace(ch,"") # 抓取关键字 texts = jieba.analyse.extract_tags(words, topK=10, withWeight=False, allowPOS=()) # 如果有多则回覆,可使用 list 去存放 reply = [ TextSendMessage(text="meow 认为这篇文章的关键字如下:\n"), TextSendMessage(text="\n".join(texts)) ] except: reply = TextSendMessage(text="您的档案可能非文字档。") line_bot_api.reply_message(event.reply_token, reply)
Location message 应用
LocationSendMessage 参数如下:
title 位置资讯的标题
address 该点的名称
latitude 经度
longitude 纬度
範例程式码
@handler.add(MessageEvent)def handle_message(event):line_bot_api.reply_message(event.reply_token, LocationSendMessage(title='Location message test', address='辅仁大学', latitude = 25.03659458277292, longitude = 121.43222234092521))
而如果现在你的 Line bot 要做一个周遭美食地图,或是实境解谜游戏时,借助 Location message 的资讯会是一个不错的主意,例如说,当使用者送出一个 Location message 后,可以计算出离该位置距离 1km 以内的美食资讯给使用者。或着当使用者送出一个 Location message 后,告知使用者离任务地点距离多远以及所在方向。以上这些都会需要去计算到经纬度的距离,下面则是範例的程式码。
import math# 经纬度距离计算公式def getDistance(latA, lonA, latB, lonB): ra = 6378140 # radius of equator: meter rb = 6356755 # radius of polar: meter flatten = (ra - rb) / ra # Partial rate of the earth # change angle to radians radLatA = math.radians(latA) radLonA = math.radians(lonA) radLatB = math.radians(latB) radLonB = math.radians(lonB) pA = math.atan(rb / ra * math.tan(radLatA)) pB = math.atan(rb / ra * math.tan(radLatB)) x = math.acos(math.sin(pA) * math.sin(pB) + math.cos(pA) * math.cos(pB) * math.cos(radLonA - radLonB)) c1 = (math.sin(x) - x) * (math.sin(pA) + math.sin(pB))**2 / math.cos(x / 2)**2 c2 = (math.sin(x) + x) * (math.sin(pA) - math.sin(pB))**2 / math.sin(x / 2)**2 dr = flatten / 8 * (c1 - c2) distance = ra * (x + dr) return math.round(distance,3) @handler.add(MessageEvent)def handle_message(event):print(event.message.latitude)distance = getDistance(event.message.latitude, event.message.longitude, 25.03659458277292, 121.43222234092521)line_bot_api.reply_message(event.reply_token, TextSendMessage(text="离辅大的距离为:" + str(distance) + "m"))