多功能小应用软件
# -*- coding: utf-8 -*-"""
Created on Sat Mar 26 17:06:29 2016
@author: Administrator
"""
from Tkinter import *
import urllib2
import urllib
import json
import gzip
import zlib
from gzip import GzipFile
from StringIO import StringIO
from urlparse import urlparse
import poplib,email
from email.header import decode_header,Header
from email.mime.text import MIMEText
from email.parser import Parser
from email.utils import parseaddr
import smtplib
import time
import os,sys
import random
class show:
def __init__(self):
self.respons = '宝宝上线啦!!'#用存放指令
self.kongzhi = 50
self.p = poplib.POP3('pop3.163.com')
#self.send_mail()
self.flag = 1
self.target = ' '
self.content = ' '
self.city_name = ' '
self.weather_dict = {}
self.root = Tk()
#框架题目
self.root.title("麒麟比赛小程序")
#图形界面的大小 长X宽
self.root.geometry('800x400')
self.frm = Frame(self.root)
print(13)
#self.frm.bind("<Leave>", self.event_print)
print(14)
#标题
Label(self.root, text = '智能翻译&&实时天气', font=('Verdana',20), fg = 'red').pack(side = TOP)
self.frm = Frame(self.root)
self.frm_L = Frame(self.frm)
#left:TOP
self.frm_LT = Frame(self.frm_L)
self.trans_content = StringVar()
self.e1 = Entry(self.frm_LT, textvariable = self.trans_content, width = 10)
self.e1.pack(side = RIGHT)
Label(self.frm_LT, text = '翻译内容:', font = ('Arial', 15)).pack(side = LEFT)
#显示左边顶端布局
self.frm_LT.pack()
#显示左边布局
self.frm_L.pack(side = LEFT)
#显示翻译内容
self.t_show_L = Text(self.frm_L, width = 15, height = 10, font = ('Verdana',15))
self.t_show_L.insert('1.0', '')
#显示文本内容
self.t_show_L.pack()
Button(self.frm_L, text = '查询', font = ("Arial, 15"), command = self.search).pack(side = LEFT)
Button(self.frm_L, text = '发音', font = ("Arial, 15"), command = self.speak_word).pack(side = RIGHT)
#mid:top
self.frm_M = Frame(self.frm)
self.frm_MT = Frame(self.frm_M)
self.address = StringVar()
self.e3 = Entry(self.frm_MT, textvariable = self.address, width = 25)
self.e3.pack(side=RIGHT)
Label(self.frm_MT,text = '邮箱地址:',font = ('Arial', 15)).pack(side = LEFT)
self.frm_MT.pack()
self.frm_MS = Frame(self.frm_M)
Label(self.frm_MS,text = '主题:',font = ('Arial', 15)).pack(side = LEFT)
self.topic = StringVar()
self.e4 = Entry(self.frm_MS, textvariable = self.topic, width = 25)
self.e4.pack(side=RIGHT)
self.frm_MS.pack()
self.t_input_M = Text(self.frm_M, width = 20, height = 5, font = ('Verdana',15))
self.t_input_M.pack()
self.frm_M.pack(side=LEFT)
Button(self.frm_M, text = '发送邮件', font = ("Arial, 15"), command = self.send_mail_1).pack(side = LEFT)
Button(self.frm_M, text = '读取邮件', font = ("Arial, 15"), command = self.read_email).pack(side = RIGHT)
#right: TOP
self.frm_R = Frame(self.frm)
self.frm_RT = Frame(self.frm_R)
self.city_name = StringVar()
self.e2 = Entry(self.frm_RT, textvariable = self.city_name, width = 10)
self.e2.pack(side = RIGHT)
Label(self.frm_RT, text = '城市:', font = ('Arial', 15)).pack(side = LEFT)
#显示右边顶端布局
self.frm_RT.pack()
#显示右边布局
self.frm_R.pack(side = RIGHT)
#self.frm_R.bind("<Leave>", self.event_print)
#显示查询城市的信息
self.t_show_R = Text(self.frm_R, width = 15, height = 10, font = ('Verdana',15))
self.t_show_R.insert('1.0', '')
#显示右边文本内容
self.t_show_R.pack()
self.t_show_R.bind("<Leave>", self.listen_email)
Button(self.frm_R, text = '查询', font = ("Arial, 15"), command = self.show_weather).pack()
#显示整个布局
self.frm.pack()
#显示翻译结果函数
def search(self):
if isinstance(self.e1.get(), unicode):
self.flag = 0
self.content = self.e1.get().encode('utf-8')
self.trans()
self.t_show_L.delete('1.0', '100.0')
self.t_show_L.insert('1.0', '结果:' + self.target)
#将翻译的内容self.content发送到有道客户端翻译,获得翻译结果self.target
def trans(self):
#利用网络,使用有道客户端
url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=https://www.baidu.com/s'
#对有道客户端必须发出指令,Method :post
data = {}
head = {}
head['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 BIDUBrowser/8.1 Safari/537.36'
data['type'] = 'AUTO'
data['i'] = self.content
data['doctype'] = 'json'
data['xmlVersion'] = '1.6'
data['keyfrom'] = 'fanyi.web'
data['ue'] = 'UTF-8'
data['action'] = 'FY_BY_CLICKBUTTON'
data['typoResult'] = 'true'
#转换编码
data = urllib.urlencode(data).encode('utf-8')
#print(data)
req = urllib2.Request(url, data, head)
#获取翻译结果的网站
response = urllib2.urlopen(req)
#读取网站的内容,此时网站的编码形式是json
html = response.read().decode('utf-8')
print(html)
#将网站的内容进行转换从json语言到python,得到的是一个字典数据
self.target = json.loads(html)
print (self.target)
self.target = self.target['translateResult']['tgt'].encode('utf-8')
print(self.target)
def get_weather_data(self) :
self.city_name = self.e2.get().encode('utf-8')
url1 = 'http://wthrcdn.etouch.cn/weather_mini?city='+urllib2.quote(self.city_name)
#url2 = 'http://wthrcdn.etouch.cn/weather_mini?citykey=101010100'
#网址1只需要输入城市名,网址2需要输入城市代码
#print(url1)
encoding_support = ContentEncodingProcessor
opener = urllib2.build_opener(encoding_support, urllib2.HTTPHandler)
weather_data_1 = opener.open(url1).read()
#解压网页数据
print (weather_data_1)
#将json语言转化为python
weather_dict_1 = json.loads(weather_data_1)
#将json数据转换为dict数据
return weather_dict_1
#
def show_weather(self):
self.weather_dict = self.get_weather_data()
#将json数据转换为dict数据
if self.weather_dict.get('desc') == 'invilad-citykey':
self.t_show_R.delete('1.0', '100.0')
#在text 里面开始从第一行输入
self.t_show_R.insert('1.0', '你输入的城市名有误,或者天气中心未收录你所在城市')
elif self.weather_dict.get('desc') == 'OK':
forecast = self.weather_dict.get('data').get('forecast')
self.t_show_R.delete('1.0', '100.0')
self.t_show_R.insert('1.0','日期:'+forecast.get('date').encode('utf-8')+'\n')
self.t_show_R.insert('2.0','城市:'+self.weather_dict.get('data').get('city').encode('utf-8')+'\n')
self.t_show_R.insert('3.0', '温度:' +self.weather_dict.get('data').get('wendu').encode('utf-8')+'℃'+'\n')
self.t_show_R.insert('4.0', '感冒:' +self.weather_dict.get('data').get('ganmao').encode('utf-8')+'\n')
self.t_show_R.insert('5.0','风向:'+forecast.get('fengxiang').encode('utf-8')+'\n')
self.t_show_R.insert('6.0','风级:'+forecast.get('fengli').encode('utf-8')+'\n')
self.t_show_R.insert('7.0','高温:'+forecast.get('high').encode('utf-8')+'\n')
self.t_show_R.insert('8.0','低温:'+forecast.get('low').encode('utf-8')+'\n')
self.t_show_R.insert('9.0','天气:'+forecast.get('type').encode('utf-8')+'\n')
for i in :
print(forecast.get('date'))
print(i)
#此处插入有点问题
self.t_show_R.insert('10.0','日期:'+forecast.get('date').encode('utf-8')+'\n')
self.t_show_R.insert('11.0','风向:'+forecast.get('fengxiang').encode('utf-8')+'\n')
self.t_show_R.insert('12.0','风级:'+forecast.get('fengli').encode('utf-8')+'\n')
self.t_show_R.insert('13.0','高温:'+forecast.get('high').encode('utf-8')+'\n')
self.t_show_R.insert('14.0','低温:'+forecast.get('low').encode('utf-8')+'\n')
self.t_show_R.insert('15.0','天气:'+forecast.get('type').encode('utf-8')+'\n')
def read_email(self):
self.t_input_M.delete('1.0', '100.0')
self.e3.delete(0, END)
self.e4.delete(0, END)
self.p = poplib.POP3('pop3.163.com')
#与服务器终端交换信息
self.p.set_debuglevel(1)
self.p.user('xxxxxxxxxxxxx@163.com')
self.p.pass_('xxxxxxxxxxxxx')
#返回三个参数
self.res, self.mails, self.octets = self.p.list()
#邮件数
index = len(self.mails)
#读取最新一份邮件数据
self.res, self.lines, self.octets = self.p.retr(index)
#处理信息,规范文本
self.msg_content = b'\r\n'.join(self.lines).decode('utf-8')
#解析文本
self.msg = Parser().parsestr(self.msg_content)
#调用函数
self.print_info(self.msg,index)
self.e3.insert(0, self.address_read)
self.e4.insert(0, self.subject_read)
self.t_input_M.insert('1.0', self.content_read)
def listen_email(self,event): #查看邮箱
print(event.x)
try:
#打开接收邮件终端
self.p = poplib.POP3('pop3.163.com')
#与服务器终端交换信息
self.p.set_debuglevel(1)
self.p.user('xxxxxxxxxxx@163.com')
self.p.pass_('xxxxxxxxxxxx')
#返回三个参数
self.res, self.mails, self.octets = self.p.list()
#邮件数
index = len(self.mails)
#读取最新一份邮件数据
self.res, self.lines, self.octets = self.p.retr(index)
#处理信息,规范文本
self.msg_content = b'\r\n'.join(self.lines).decode('utf-8')
#解析文本
self.msg = Parser().parsestr(self.msg_content)
#调用函数
self.print_info(self.msg,index)
except:
print('没有邮件,请发指令')
#sys.exit()
#self.listen_email()
self.p.quit()
def speak_word(self):
self.file = open('word.vbs', 'wb')
self.content = self.e1.get().encode('utf-8')
if self.flag == 0:
self.content = self.target
self.flag = 1
self.str2 = 'CreateObject("SAPI.SpVoice").speak"'+self.content+'"'
self.file.write(self.str2)
self.file.close()
os.system('cscript word.vbs')
def speak(self, cont): #实现电脑语音
self.file=open('tmp.vbs','wb')
self.str1='CreateObject("SAPI.SpVoice").speak"'+cont+'"'
print type(cont)
self.file.write(self.str1.encode('gbk'))
self.file.close()
os.system('cscript tmp.vbs')
self.respons = '你是谁?'
self.send_mail()
self.kongzhi = 1
def shut_down(self): #关机
print('正在关机......')
os.system('shutdown -f -s -t 10 -c closing...')
self.respons = '已关机'
self.send_mail()
self.kongzhi = 2
sys.exit()
def guess_charset(self,msg):
#查找编码类型
charset = msg.get_charset()
if charset is None:
content_type = msg.get('Content-Type', '').lower()
pos = content_type.find('charset=')
if pos >= 0:
charset = content_type.strip()
return charset
def decode_str(self,s):
value, charset = decode_header(s)
if charset:
value = value.decode(charset)
return value
def send_mail_1(self): #发送邮件
try:
self.content_3 = self.t_input_M.get(1.0,END).encode("utf-8")
#print self.content_3
self.sender = 'xxxxxxxxxxxxx@163.com'
self.receiver_1 = self.e3.get().encode('gbk')
#print self.receiver_1
self.subject = self.e4.get()
#print self.subject
self.username = 'xxxxxxxxx@163.com'
self.password = 'xxxxxxx'
self.msg_send = MIMEText(self.content_3,'plain','utf-8')
self.msg_send['Subject'] = Header(self.subject, 'utf-8')
self.msg_send['From'] = 'xxxxxxxx@163.com'
self.msg_send['To'] = self.receiver_1
self.smtp = smtplib.SMTP()
self.smtp.connect('smtp.163.com')
self.smtp.login(self.username,self.password)
self.smtp.sendmail(self.sender,self.receiver_1,self.msg_send.as_string())
self.smtp.quit()
except:
print 'sorry'
#self.send_mail()
def send_mail(self): #发送邮件
try:
self.sender = 'xxxxxxxxx@163.com'
self.receiver = 'xxxxxxxxxxxx@qq.com'
self.subject = self.respons
self.username = 'xxxxxxxxx@163.com'
self.password = 'xxxxxxxxxxxxx'
self.msg_send = MIMEText(self.respons,'plain','utf-8')
self.msg_send['Subject'] = Header(self.subject, 'utf-8')
self.msg_send['From'] = 'xxxxxxx@163.com'
self.msg_send['To'] = "xxxxxxxxxxxx@qq.com"
self.smtp = smtplib.SMTP()
self.smtp.connect('smtp.163.com')
self.smtp.login(self.username,self.password)
self.smtp.sendmail(self.sender,self.receiver,self.msg_send.as_string())
self.smtp.quit()
except:
print 'sorry'
#self.send_mail()
def print_info(self, msg,num, indent=0):
if indent == 0:
for header in ['From', 'To', 'Subject']:
value = msg.get(header, '')
if value:
if header=='Subject':
value = self.decode_str(value)
self.subject_read= value
print value
elif header =='From':
hdr, addr = parseaddr(value)
self.address_read=addr
print addr
else:
hdr, addr = parseaddr(value)
name = self.decode_str(hdr)
#print type(addr)
value = u'%s <%s>' % (name, addr)
#print header
#print('%s%s: %s' % ('' * indent, header, value))
if (msg.is_multipart()):
print msg.is_multipart()
parts = msg.get_payload()
for n, part in enumerate(parts):
#print('%spart %s' % ('' * indent, n))
#print('%s--------------------' % ('' * indent))
self.print_info(part, indent + 1)
else:
content_type = msg.get_content_type()
if content_type=='text/plain':
content = msg.get_payload(decode=True)
charset = self.guess_charset(msg)
if charset:
content = content.decode(charset)
if content == 'shutdown':
self.shut_down()
elif content == 'speak':
self.speak(content)
self.p.dele(num)
# or content_type=='text/html'
self.content_read = content
print('%sText: %s' % ('' * indent, content + '...'))
else:
print('%sAttachment: %s' % ('' * indent, content_type))
class ContentEncodingProcessor(urllib2.BaseHandler):
"""A handler to add gzip capabilities to urllib2 requests """
# add headers to requests
def http_request(self, req):
req.add_header("Accept-Encoding", "gzip, deflate")
return req
# decode
def http_response(self, req, resp):
old_resp = resp
# gzip
if resp.headers.get("content-encoding") == "gzip":
gz = GzipFile(
fileobj=StringIO(resp.read()),
mode="r"
)
resp = urllib2.addinfourl(gz, old_resp.headers, old_resp.url, old_resp.code)
resp.msg = old_resp.msg
# deflate
if resp.headers.get("content-encoding") == "deflate":
gz = StringIO( deflate(resp.read()) )
resp = urllib2.addinfourl(gz, old_resp.headers, old_resp.url, old_resp.code)# 'class to add info() and
resp.msg = old_resp.msg
return resp
# deflate support
def deflate(data): # zlib only provides the zlib compress format, not the deflate format;
try: # so on top of all there's this workaround:
return zlib.decompress(data, -zlib.MAX_WBITS)
except zlib.error:
return zlib.decompress(data)
if __name__ == '__main__':
print(11)
show()
mainloop()
#qmail.listen_email()
#if qmail.kongzhi == 1:
# continue
#elif qmail.kongzhi == 2:
# break
支持楼主 666、
{:10_256:}{:10_256:
页:
[1]