异度部落格

学习是一种生活态度。

0%

NNTP 连接主要是用在新闻组的消息上面,下面的代码演示了 NNTP 连接的建立,不过显然下面的那个新闻组客户端程序是不能用的。

#!/usr/bin/env python
#新闻组客户端程序
import nntplib
import socket
HOST = 'your.nntp.server'
GRNM = 'comp.lang.python'
USERNAME = 'Killua'
PASSWORD = '123456'
def NNTPClient():
try:
n = nntplib.NNTP(HOST)
except socket.gaierror, e:
print 'ERROR: cannot connect host "%s"' % HOST
print '("%s")' % eval(str(e))[1]
return
except nntplib.NNTPPermanentError, e:
print 'ERROR: access denied on "%s"' % HOST
print '("%s")' % str(e)
return
print '>> Connected to host "%s"' % HOST
try:
rsp, ct, fst, lst, grp = n.group(GRNM)
except nntplib.NNTPTemporaryError, e:
print 'ERROR: cannot load group "%s"' % GRNM
print '("%s")' % str(e)
print 'Server may require authentication'
print 'Uncomment/Edit login lne above'
n.quit()
return
except nntplib.NNTPTemporaryError, e:
print 'ERROR: group "%s" unavailable' % GRNM
print '("%s")' % str(e)
n.quit()
return
print '>> Found newgroup "%s"' % GRNM
rng = '%s-%s' % (lst,lst)
rsp, frm = n.xhdr('from', rng)
rsp, sub = n.xhdr('subjec', rng)
rsp, dat = n.xhdr('date', rng)
print ''' Found last article(#%s):
From: %s
Subject: %s
Date: %s
''' (lst, frm[0][1], sub[0][1], dat[0][1])
def displayFirst20(data):
'Display First 20 lines'
count = 0
lines = (line.rstrip() for line in data)
lastBlank = True
for line in lines:
if line:
lower = line.lower()
if (lower.startswith('>') and /
not lower.startswith('>>>')) or /
lower.startswith('|') or /
lower.startswith('in article') or /
lower.endswith('writes:') or /
lower.endswith('wrote:'):
continue
if not lastBlank or (lastBlank and line):
print '%s' % line
if line:
count += 1
lastBlank = False
else:
lastBlank = True
if count == 20:
break
def main():
NNTPClient()
DisplayFirst20()
if __name__ == '__main__':
main()

E-Mail 的收发涉及到 STMP 和 POP3 两个协议。下面的代码演示了 STMP 和 POP3 连接的建立

#!/usr/bin/env python
#E-Mail客户端
from smtplib import SMTP
from poplib import POP3
from time import sleep
SMTPSVR = 'stmp.163.com'
POP3SVR = 'pop.163.com'
FROMMAIL = 'killua_hzl@163.com'
TOMAIL = 'killua_hzl@163.com'
origHdrs = ['From: %s' % FROMMAIL,
'To: %s' % TOMAIL,
'Subject: Just for test']
origBody = ['Test1','Test2','Test3']
origMsg = '/r/n/r/n'.join(['/r/n'.join(origHdrs),
'/r/n'.join(origBody)])
sendSvr = SMTP(SMTPSVR)
errs = sendSvr.sendmail(FROMMAIL, TOMAIL, origMsg)
sendSvr.quit()
assert len(errs) == 0, errs
sleep(10) #wait for mail to be delivered
recvSvr = POP3(POP3SVR)
recvSvr.user('killua_hzl')
recvSvr.pass_('123456')
rsp, msg, size = recvSvr.retr(recvSvr.stat()[0])
sep = msg.index('')
recvBody = msg[sep + 1]
assert origBody == recvBody

首先用 Qt Designer 创建窗体后,保存为 form.ui

然后再 cmd 中输入

pyuic4 -o ui_form.py form.ui

之后对应目录下生成 ui_form.py 的文件

附上 pyuic4 的帮助

NAME
pyuic4 - compile Qt4 user interfaces to Python code
SYNOPSIS
pyuic4 [OPTION]... FILE
DESCRIPTION
pyuic4 takes a Qt4 user interface description file and compiles it to
Python code. It can also show a preview of the user interface.
OPTIONS
-h, --help
Show a summary of the options.
--version
Display the version number of pyuic4 of the version of Qt which
PyQt4 was generated for.
-p, --preview
Show a preview of the UI instead of generating Python code.
-o, --output=FILE
Write the generated Python code to FILE instead of stdout.
-d, --debug
Show detailed debugging information about the UI generation
process.
-x, --execute
Generate extra code to test and display the class when executed
as a script.
-i, --indent=NUM
Set the indentation width to NUM spaces. A TAB character will be
used if NUM is 0 (default: 4).

晚上无聊看了点 C#,随便写了个 Hello World 做纪念

using System;
namespace MyNamespace
{
class MyClass
{
static void Main()
{
Console.WriteLine("Hello World");
Console.ReadLine();
return ;
}
}
}

保存为 helloworld.cs,然后再 cmd 里面执行

csc helloworld.cs

会在源文件的目录下面生成一个 helloworld.exe 的可执行程序

#!/usr/bin/env python
#-*- coding:utf-8 -*-
#6–2. 字符串标识符.修改例6-1 的idcheck.py 脚本,使之可以检测长度为一的标识符,并且
#可以识别Python 关键字,对后一个要求,你可以使用keyword 模块(特别是keyword.kelist)来帮你.
import string
import keyword
alphas = string.letters
nums = string.digits
print 'The Identifier Checker'
myString = raw_input('Input the identifier to check:')
if myString in keyword.kwlist :
print 'Invalid: It is a keyword.'
else:
if myString[0] not in alphas + '_' :
print 'Invalid: First symbol must be alphabetic or underline.'
else:
for c in myString[1:] :
if c not in alphas + nums :
print 'Invalid: Symbols must be alphabetic or numbers.'
print 'The identifier is ok.'
#!/usr/bin/env python
#-*- coding:utf-8 -*-
#6–3. 排序
#(a) 输入一串数字,从大到小排列之.
#(b) 跟a 一样,不过要用字典序从大到小排列之.
#(a)
list1 = []
while True:
n = int(raw_input('输入一些数字以0结束:'))
if n == 0:
break
list1.append(n)
list1.sort()
print list1
#(b)
list2 = []
while True:
n = raw_input('输入一些数字以0结束:')
if n == '0':
break
list2.append(n)
list2.sort()
print list2
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#6–6. 字符串.创建一个string.strip()的替代函数:接受一个字符串,去掉它前面和后面的空格
str = raw_input('Input a string your want to operate:')
i = 0
j = len(str) - 1
while str[i] == ' ' :
i += 1

while str[j] == ' ' :
j -= 1

str = str[i:j+1]
print str
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#6–9. 转换.为练习5-13 写一个姊妹函数, 接受分钟数, 返回小时数和分钟数. 总时间不
#变,并且要求小时数尽可能大.
n = int(raw_input('输入分钟数:'))
hour = n / 60
min = n % 60
print '%d : %d' % (hour, min)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#6–10.字符串.写一个函数,返回一个跟输入字符串相似的字符串,要求字符串的大小写反转.
#比如,输入"Mr.Ed",应该返回"mR.eD"作为输出.
def mySwapcase(myString) :
return myString.swapcase()

str = raw_input('Input a string your want to operate:')
print mySwapcase(str)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#6–12.字符串
#(a)创建一个名字为findchr()的函数,函数声明如下:def findchr(string, char)
#findchr()要在字符串string 中查找字符char,找到就返回该值的索引,否则返回-1.不能用
#string.*find()或者string.*index()函数和方法
#(b)创建另一个叫rfindchr()的函数,查找字符char 最后一次出现的位置.它跟findchr()工作
#类似,不过它是从字符串的最后开始向前查找的.
#(c)创建第三个函数,名字叫subchr(),声明如下:def subchr(string, origchar, newchar)
#subchr()跟findchr()类似,不同的是,如果找到匹配的字符就用新的字符替换原先字符.返回
#修改后的字符串.
def findchr(string, char) :
i = 0;
while i < len(string) :
if string[i] == char :
return i
i += 1
return -1

def rfindchr(string, char) :
i = len(string) - 1
while i >= 0 :
if string[i] == char :
return i
i -= 1
return -1

def subchr(myString, origchar, newchar) :
'将string中的origchar字符替换成newchar字符'
import string
string.replace(myString,origchar,newchar)

#Test
myString = 'abcdefcg'
print findchr(myString, 'c')
print findchr(myString, 'c')
subchr(myString, 'c', 'X')
print myString

ibus 是一个很强大的输入,现在主要用于手机和 Linux 平台上。

下面是 ibus 日语输入法 ibus-anthy 的安装方法

sudo apt-get install ibus-anthy

然后在 ibus 的首选项里面添加日语->anthy 即可

本人一直感觉天书棋谈这个游戏很2,感觉电脑很是弱智。今天把一个增强库装了以后,一把都没赢过...悲剧了 增强库安装方法如下:

sudo apt-get install libeval0-dev 

下面的代码是这两天看 Python 核心编程的时候做的部分课后练习

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#5-2 运算符
#(a) 写一个函数,计算并返回两个数的乘积
#(b) 写一段代码调用这个函数,并显示它的结果
def mult(x,y) :
'返回两个数x和y的乘积'
return int(x) * int(y) #这里int()函数还是要的
a = raw_input('输入数a:')
b = raw_input('输入数b:')
print 'a * b = ', mult(a,b)
#!/usr/bin/env python
#-*- coding: utf-8 -*-
#5-3 标准类型运算符. 写一段脚本,输入一个测验成绩,根据下面的标准,输出他的评分成绩(A-F)。
#A: 90–100 B: 80–89 C: 70–79 D: 60 F: <60
while True :
score = raw_input('输入分数:')
score = int(score) #将score类型由string转换为int
if score > 100 or score < 0 :
print '输入分数无效,程序退出'
break
elif score >= 90 :
print '%d is rank A' % score
elif score >= 80 :
print '%d is rank B' % score
elif score >= 70 :
print '%d is rank C' % score
elif score >= 60:
print '%d is rank D' % score
else :
print '%d is rank F' % score
#!/usr/bin/env python
#-*- coding: utf-8 -*-
#5-4 取余。判断给定年份是否是闰年。使用下面的公式:
#一个闰年就是指它可以被4 整除,但不能被100 整除, 或者它既可以被4 又可以被100 整
#除。比如 1992,1996 和2000 年是闰年,但1967 和1900 则不是闰年。下一个是闰年的整世
#纪是 2400 年。
def isLeap(year) :
year = int(year)
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0 :
return True
else :
return False

year = raw_input('输入一个年份:')
if (isLeap(year)) :
print year, '是闰年'
else :
print year, '不是闰年'
#!/usr/bin/env python
#-*- coding:utf-8 -*-
#5-5 取余。取一个任意小于1 美元的金额,然后计算可以换成最少多少枚硬币。硬币有1
#美分,5 美分,10 美分,25 美分四种。1 美元等于100 美分。举例来说,0.76 美元换算结果
#应该是 3 枚25 美分,1 枚1 美分。类似76 枚1 美分,2 枚25 美分+2 枚10 美分+1 枚5 美分+1
#枚1 美分这样的结果都是不符合要求的。
money = raw_input('输入任意小于1 美元的金额:')
print money,'美元换算结果'
money = float(money)
money *= 100
money = int(money)
cent25 = money / 25
money %= 25
cent10 = money / 10
money %= 10
cent5 = money / 5
money %= 5
cent1 = money
if cent25 :
print '25美分*',cent25
if cent10 :
print '10美分*',cent10
if cent5 :
print '5美分*',cent5
if cent1 :
print '1美分*',cent1
#!/usr/bin/env python
#-*- coding:utf-8 -*-
#5-6 算术。写一个计算器程序 你的代码可以接受这样的表达式,两个操作数加一个运算符:
#N1 运算符 N2. 其中 N1 和 N2 为整数或浮点数,运算符可以是+, -, *, /, %, ** 分别表示
#加法,减法, 乘法, 整数除,取余和幂运算。计算这个表达式的结果,然后显示出来。提示:
#可以使用字符串方法 split(),但不可以使用内建函数 eval().
def operator(str) :
if str.find('+') >= 0:
return '+'
elif str.find('-') >= 0:
return '-'
elif str.find('*') >= 0:
return '*'
elif str.find('/') >= 0:
return '/'
elif str.find('%') >= 0:
return '%'
else :
return '**'
calStr = raw_input('输入计算表达式,如a+b形式:')
op = operator(calStr)
num = calStr.split(op)
print num
res = 0.0
if op == '+':
res = float(num[0]) + float(num[1])
elif op == '-':
res = float(num[0]) - float(num[1])
elif op == '*':
res = float(num[0]) * float(num[1])
elif op == '/':
res = float(num[0]) / float(num[1])
elif op == '%':
res = int(num[0]) % int(num[1])
elif op == '**':
res = float(num[0]) ** float(num[1])
print 'result is %f' % str(res)
#!/usr/bin/env python
#-*- coding:utf-8 -*-
#5-10 转换。写一对函数来进行华氏度到摄氏度的转换。转换公式为C = (F - 32) * (5 / 9)
#应该在这个练习中使用真正的除法, 否则你会得到不正确的结果。
F = float(raw_input('输入温度:'))
C = (F-32)*(5/9.0)
print '华氏度到摄氏度的转换后,结果为:',C
#!/usr/bin/env python
#-*- coding:utf-8 -*-
#5-11 取余。
#(a) 使用循环和算术运算,求出 0-20 之间的所有偶数
#(b) 同上,不过这次输出所有的奇数
#(c) 综合 (a) 和 (b), 请问辨别奇数和偶数的最简单的方法是什么?
#(d) 使用(c)的成果,写一个函数,检测一个整数能否被另一个整数整除。 先要求用户输
#入两个数,然后你的函数判断两者是否有整除关系,根据判断结果分别返回 True 和 False;
#(a)
print '0-20 之间的所有偶数:'
i = 0
while i <= 20 :
if (i % 2 == 0) :
print i,' '
i += 1
print
#(b)
print '0-20 之间的所有奇数:'
i = 0
while i <= 20 :
if (i % 2 == 1) :
print i,' '
i += 1
print
#(d)
a = int(raw_input('输入整数a:'))
b = int(raw_input('输入整数b:'))
if (a % b == 0):
print 'a能被b整除'
else:
print 'a不能b整除'
#!/usr/bin/env python
#-*- coding:utf-8 -*-
#5–15. 最大公约数和最小公倍数。请计算两个整数的最大公约数和最小公倍数。
def GCD(a, b):
'求a和b的最大公约数'
if b == 0 :
return a
else :
return GCD(b, a % b)
def LCM(a, b):
'求a和b的最小公倍数'
if (a * b == 0):
return 0
else :
return a * b / GCD(a,b)

x = int(raw_input('输入x:'))
y = int(raw_input('输入y:'))
print 'GCD:',GCD(x, y)
print 'LCM:',LCM(x, y)

多个signals连接一个slot的时候,可以使用QObject::sender()函数进行读取所产生的对象,之后只要加一个强制类型转换就ok了

实例如下:

连接部分:

connect(ui->button0, SIGNAL(clicked()), this, SLOT(append()));
connect(ui->button1, SIGNAL(clicked()), this, SLOT(append()));

slot实现部份:

QObject *object = QObject::sender();
QPushButton *sender = qobject_cast<QPushButton *>(object);