This is a few days to do python, here are some of the code I collected, you can see, Python is really interesting.
1. Generate random numbers
Import random #这个是注释, introducing modules
Rnd = random number between random.randint (1,500) #生成1-500
2. Read files
f = open ("C://1.txt", "R")
lines = F.readlines () #读取全部内容
For line in lines
Print Line
3. Write a file
f = open ("C://1.txt", "r+") #可读可写模式
F.write ("123") #写入字符串
4. Regular expression, read Tomcat log and print date
Import re
REGX = "/d/d/d/d-/d/d-/d+"
f = open ("C:/stdout.log", "R")
i = 0
For STR in f.readlines ():
If Re.search (REGX,STR):
Response.Write (str+ "<br>")
If i>10:break# is tested, only 10 lines are parsed
I=i+1
F.close ();
5. Connecting to a database
Import Pgdb
conn = pgdb.connect (host= ' localhost ', databse= ' Qingfeng ', user= ' Qingfeng ', password= ' 123 ')
cur = conn.cursor ()
Cur.execute ("SELECT * FROM Dream")
Print Cur.rowcount
6. There are several examples of network programming and RPC, the code is too long, specifically see http://www.javaeye.com/viewtopic.php?t=10115
7. Sax Processing xml:
Import string
From Xml.sax import Saxlib, saxexts
Class Quotationhandler (Saxlib. Handlerbase):
"" "Crude sax Extractor for QUOTATIONS.DTD document" "
def __init__ (self):
Self.in_quote = 0
Self.thisquote = ' '
def startdocument (self):
print '---Begin Document---'
def startelement (self, Name, attrs):
if name = = ' Quotation ':
print ' quotation: '
Self.in_ Quote = 1
else:
Self.thisquote = Self.thisquote + ' {'
def endelement (self, name):
if name = = ' Quotation ':
Print String.Join (String.Split ( SELF.THISQUOTE[:230]) + ' ... ',
print ' (' +str len (self.thisquote) + ' bytes)/n '
self.thisquote = '
self.in_quote = 0
Else:
Self.thisquote = Self.thisquote + '} '
def characters (self, ch, start, length):
If Self.in_quote:
Self.thisquote = Self.thisquote + ch[start:start+length]
if __name__ = = ' __main__ ':
Parser = saxexts. Xmlparserfactory.make_parser ()
Handler = Quotationhandler ()
Parser.setdocumenthandler (Handler)
Parser.parsefile (Open ("Sample.xml"))
Parser.close ()
8.python GUI module Standard is Tkinter, also has Qt and MFC module, interested everyone to search their own under
Import Tkinter
root=tkinter.tk ()
MyLabel (Root, "Welcome to Python's World")
Mylabel.pack ()
Root.mainloop ()