异度部落格

学习是一种生活态度。

0%

这里主要使用了一个 random 随机模块中的 randint 和 choice。Python 的随机模块还是很强大的。

#!/usr/bin/env python
#随机数据生成
from random import randint,choice
from string import lowercase
from sys import maxint
from time import ctime
def randDataGenerate () :
doms = ('sina.com', '163.com', 'cctv.cn', 'yahoo.com.cn', 'csdb.net')

for i in range(randint(5, 20)) :
#随机日期生成
dateInt = randint(0, maxint - 1)
dateStr = ctime(dateInt)
#随机E-Mail地址生成
email = ''
for j in range(randint(4, 7)) :
email += choice(lowercase)
email += '@' + choice(doms)
#随机数生成
num = randint(0, 1000)
print '%s >> %s :: %d' % (dateStr, email, num)
def main() :
randDataGenerate()
if __name__ == '__main__' :
main()

这里定义了一个 TCPServer 和 TCPClient。这里创建一个 TCP 服务程序,服务器会把客户发送过来的字符串加上一个时间戳,然后显示,并返回客户端。主要后面无论如何都要记得 close()关上连接,虽然基本上不会执行那一句。

TCPServer.py

#!/usr/bin/env python
#创建一个TCP服务程序,这个程序会把客户发送过来的字符串加上一个时间戳,然后显示,并返回客户端
from socket import *
from time import ctime
HOST = ''
PORT = 20000
BUFSIZE = 1024 #1KB
ADDR = (HOST, PORT)
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)
while True:
print 'waiting for connection...'
tcpClientSock,clientAddr = tcpSerSock.accept()
print '...connected from :', clientAddr
while True:
data = tcpClientSock.recv(BUFSIZE)
if not data:
break
print '[%s] %s' % (ctime(), data)
tcpClientSock.send('[%s] %s' % (ctime(), data))
tcpClientSock.close()
tcpSerSock.close()

TCPClient.py

#!/usr/bin/env python
#创建一个TCP客户端
from socket import *
HOST = 'localhost'
PORT = 20000
BUFSIZE = 1024
ADDR = (HOST, PORT)
tcpClientSock = socket(AF_INET, SOCK_STREAM)
tcpClientSock.connect(ADDR)
while True:
data = raw_input('Enter a string your want to send >')
if not data:
break
tcpClientSock.send(data)
data = tcpClientSock.recv(BUFSIZE)
if not data:
break
print data
tcpClientSock.close()

这里定义了一个 UDPServer 和 UDPClient。这里创建一个 TCP 服务程序,服务器会把客户发送过来的字符串加上一个时间戳,然后显示,并返回客户端。

UDPServer.py

#!/usr/bin/env python
from socket import *
from time import ctime
#创建一个UDP客户端
HOST = ''
PORT = 20001
BUFSIZE = 1024
ADDR = (HOST, PORT)
udpSerSock = socket(AF_INET, SOCK_DGRAM)
udpSerSockbind(ADDR)
while True:
print 'waiting for message...'
data, addr = udpSerSock.recvfrom(BUFSIZE)
udpSerSock.sendto('[%s] %s' % (ctime(), data), addr)
print'received from %s >> %s' % (addr, data)
udpSerSock.close()

UDPClient.py

#!/usr/bin/env python
from socket import *
HOST = 'localhost'
PORT = 20001
BUFSIZE = 1024
ADDR = (HOST, PORT)
udpClientSock = socket(AF_INET, SOCK_DGRAM)
while True:
data = raw_input('Enter the message you want to send >')
if not data:
break
udpClientSock.sendto(data, ADDR)
data, ADDR = udpClientSock.recvfrom(BUFSIZE)
if not data:
break
print data
udpClientSock.close()

这里自行定义了一个 MyTime 的类,继承于系统类 object。在 Python 里面默认的情况的下都要继承于这个类。类里面对init,straddiadd函数进行了重载。其实严格上讲不能叫重载,因为 Python 不支持重载,确切说应该叫覆盖。里面我还企图对init进行再次重载,显然不允许的,放在那边做个比较。

#!/usr/bin/env python
class MyTime(object) :
'MyTime - operate hours, minutes and seconds'
def __init__(self, h, m, s) :
'MyTime - Constructor'
self.hour = h;
self.min = m;
self.sec = s;

#def __init__(self, seconds) :
# 'MyTime - Constructor'
# self.hour = seconds / 3600
# seconds = seconds % 3600
# self.min = seconds /60
# self.sec = seconds % 60

def __str__(self) : #显示函数重载
'MyTime - string representation'
return '%d : %d : %d' % (self.hour, self.min, self.sec)
__repr__ = __str__
def __add__(self, time) : #加法重载
'MyTime - overloading the addition operator'
h = m = s = 0
t = self.sec + time.sec
s = t % 60
m += t /60
t = self.min + time.min + m
m = t % 60
h = t / 60
t = self.hour + time.hour + h
h = t % 24
return self.__class__(h, m, s)

def __iadd__(self, time) : #自增重载
'MyTime - overloading the in-place addition operator'
t = self.sec + time.sec
self.sec = t % 60
self.min += t / 60
t = self.min + time.min
self.min = t % 60
self.hour += t /60
t = self.hour + time.hour
self.hour = t % 24
return self

#测试部分
t1 = MyTime(12,34,57)
t2 = MyTime(8,6,56)
print 't1 >> ', t1
print 't2 >> ', t2
print 't1 + t2 >> ', t1 + t2
t1 += t2
print 't1 += t2 >> ', t1
#测试结果
#t1 >> 12 : 34 : 57
#t2 >> 8 : 6 : 56
#t1 + t2 >> 20 : 41 : 53
#t1 += t2 >> 20 : 41 : 53

这里代码很简单,实现了一个随机序列迭代器

#!/usr/bin/env python
#随机迭代器
from random import choice
class RandSeqIterator(object) :
def __init__(self, seq) :
self.data = seq
def __iter__(self) :
return self
def next(self) :
return choice(self.data)
#Program Test
for eachItem in RandSeqIterator(('AA', 'BB', 'CC', 'DD', 'End')) :
print eachItem
if eachItem == 'End' :
break

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 = '[email protected]'
TOMAIL = '[email protected]'
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

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()

首先用 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