正好闲着无聊,于是把之前买的树莓派拿出来摆弄一下,发现还是蛮有意思。也想跟着教程做了几个小程序。
本人不太熟悉Linux系统,也不太熟悉硬件,导致一开始做的时候反复出问题,成功与否全靠信仰,不过在刷了第6遍系统后总算有点感觉了,后面也就满顺利的。
所以提醒刚学树莓派的朋友们,不要一开始就嫌麻烦直接远程登录玩,用屏幕能很直观的看到你的问题到底出在哪里。还有网上,包括淘宝客服给的很多资料都是过时的……难受。
树莓派的强大之处在于它的强大处理功能可以直接用来做服务器,很方便的处理各种用单片机处理不了的事物。
这次做的东西是个练习产物,包含了天气预报,定时闹钟,语音转化,聊天机器人等的综合项目。只贴出python代码部分
说明:
原理:将树莓派作为服务器(或者连接终端),写入python代码,分别调用爬虫机器人(requests+bs4+re),百度语音api,图灵聊天,和微信接口itchat库完成这个微信小项目。
一,实验环境:
1.树莓派3,python3.6环境
2.安装 requests,beautifulsoup4,itchat,baidu-aip库,调用time和re模块
3.申请百度语音转译账户:http://yuyin.baidu.com/
申请图灵机器人账户:http://www.tuling123.com/
详细使用文档见相关网页:
本来想用wxpy库的,它是itchat库的封装,更加简单,但是不知为何不能发送图片和文件,所以改用了itchat接口
参考——
https://www.cnblogs.com/jmmchina/p/6692175.html
https://segmentfault.com/a/1190000009420701
二,实验代码:
后半部分看起来很复杂,但其实就是照着开发文档调用接口,很简单
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 13 19:59:30 2018
@author: 29428
"""
from aip import AipSpeech
import requests
import re
from bs4 import BeautifulSoup
import time
# from wxpy import *
import itchat
from itchat.content import *
def getHTMLText(url):
try:
r = requests.get(url,timeout = 50)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return ''
def makesoup(html):
t = time.strftime('%H:%M',time.localtime(time.time()))
txt = "现在是北京时间"+str(t)
txt += '。大家好!能听见吗?'
if html == '':
return "对不起呢,我也不知道天气如何。"
else:
soup = BeautifulSoup(html,'html.parser')
text = soup.find_all('input',{'id':"hidden_title"})
text = str(text).split('\n')[0]
data = re.search('\d.+',text).group(0) # '02月08日08时 周四 多云转阴 6/0°C">'格式
date = data.split(' ')[0]
txt += "根据气象台" + date +"发布的气象预报,"
weather = data.split(' ')[3]
txt += "阿拉善盟城区的天气为" + weather
temp = data.split(' ')[5]
if '°C' in temp:
temp = temp.replace('°C','')
if '"' in temp:
temp = temp.replace('"','')
if '>' in temp:
temp = temp.replace('>','')
temp1 = int(re.findall('-?\d{1,2}',temp)[0])
temp2 = int(re.findall('-?\d{1,2}',temp)[1])
if temp1 >= temp2:
temp_high = str(temp1)
temp_low = str(temp2)
else:
temp_high = str(temp2)
temp_low = str(temp1)
txt += ",未来12小时内,最高气温"+ temp_high+"度,最低气温"+ temp_low+"度。"
txt += "感谢您的收听,下次再见!"
return txt
def stringToMp3(strings_txt):
APPID = '……'
APIKey = '……'
SecretKey = '……'
aipSpeech = AipSpeech(APPID,APIKey,SecretKey)
result = aipSpeech.synthesis(strings_txt, 'zh', 1, {'vol': 5,'per':4,
'spd':5})
# 识别正确返回语音二进制 错误则返回dict 参照下面错误码
if not isinstance(result, dict):
with open('auido.mp3', 'wb') as f:
f.write(result)
def main():
url = "http://www.weather.com.cn/weather1d/101081213.shtml#input" #新疆阿拉善盟城区
html = getHTMLText(url)
txt = makesoup(html)
stringToMp3(txt)
# print(txt)
# os.system('auido.mp3')
main()
@itchat.msg_register(itchat.content.TEXT)
def print_content(msg):
info = itchat.search_friends(name=u'某人的微信名称')
key1 = info[0].get('UserName')
key2 = msg.get('FromUserName')
global count #设置为全局变量
if key1 == key2 :
if msg['Text'] == '天气':
itchat.send_file('auido.mp3',msg['FromUserName'])
if msg['Text'] == '测试':
pic = 'sit.png'
itchat.send_image(pic,msg['FromUserName'])
if msg['Text'] == '科学上网':
itchat.send_file('3.zip',msg['FromUserName'])
if msg['Text'] == '文字转化语音':
count = 1
if count == 1:
if msg['Text'] != "文字转化语音":
txt = msg['Text']
stringToMp3(txt)
itchat.send_file('auido.mp3',msg['FromUserName'])
count = 0
if msg['Text'] == '聊天机器人':
count = 2
if msg['Text'] == '聊天机器人再见':
count = 0
if count == 2:
reply = get_response(msg['Text'])
itchat.send(reply,msg['FromUserName'])
def get_response(msg):
# 构造了要发送给服务器的数据
apiUrl = 'http://www.tuling123.com/openapi/api'
data = {
'key' : KEY,
'info' : msg,
'userid' : 'wechat-robot',
}
try:
r = requests.post(apiUrl, data=data).json()
# 字典的get方法在字典没有'text'值的时候会返回None而不会抛出异常
return r.get('text')
# 为了防止服务器没有正常响应导致程序异常退出,这里用try-except捕获了异常
# 如果服务器没能正常交互(返回非json或无法连接),那么就会进入下面的return
except:
# 将会返回一个None
return
itchat.auto_login(hotReload=True) #登录缓存
itchat.run()
apiUrl = 'http://www.tuling123.com/openapi/api'
KEY = '……
三,实验结果