python学习笔记


(1)python教程:hello world
(2)python教程:数据类型和运算规则
(3)python教程:元组,列表,词典
(4)python教程:分支、循环
(5)python教程:函数
(6)python教程:class

(8)python教程:几行代码搞定python 设计模式

(9)python模块学习

 

http://jfy3d.iteye.com/category/51172

http://woodpecker.org.cn/abyteofpython_cn/chinese/ch03s04.html

 

python的优势主要是强大的字符串处理能力和随心所欲的脚本语言写法。
1.生成随机数

 import random  
 rnd = random.randint(1,500);


2.读文件

 f = open("c:\\1.txt","r");  
 lines = f.readlines();#读取全部内容  
 for line in lines:  
 print line  


3.写文件

 f = open("c:\\1.txt","r+");#可读可写模式  
 f.write("123");#写入字符串  


4.Python的正则表达式
读取tomcat的日志文件,并且把日期开头的内容显示出来,例如:xxxx-xx-xx

   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#由于是测试,只分析十行  
        i=i+1  
   f.close();;  


5. 抓取FarideaBBS首页的所有图片

  def farideaHttp();:    
  page = urllib.urlopen("../Boards.asp";);  
  body = page.readlines();  
  page.close();        
  return body  

 

  def anyHtml(line);
  import re  
  regx = r"""<img\s*src\s*="?(\S+);"?"""  
  match_obj = re.search(regx,line);  
  if match_obj!=None:  
    all_groups = match_obj.groups();  
  for img in all_groups:print img#这个img就是图片的链接了  

 

    lines = farideaHttp();#读取全部内容  
    for line in lines:  
        anyHtml(line);  

 

自动登录

#!/usr/bin/python
#coding=utf-8

import urllib
import urllib2
import cookielib

def post(url, data):
	req = urllib2.Request(url)
	data = urllib.urlencode(data)
	#enable cookie
	cookiefile = "cookiefile"
	cookieJar = cookielib.MozillaCookieJar(cookiefile)
	opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookieJar));
	response = opener.open(req, data)
	cookieJar.save()
	#print response.read()

	#second http request use cookie
	cookieJar = cookielib.MozillaCookieJar(cookiefile)
	cookieJar.load()
	url = "http://www.xiami.com"
	opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookieJar))
	response = opener.open(url)
	print response.read()

def main():
	posturl = "http://www.xiami.com/member/login"
	data = {'email':'myemail', 'password':'mypass', 'autologin':'1', 'submit':'登 录', 'type':''}
	#print post(posturl, data)
	post(posturl, data)

if __name__ == '__main__':
	main()


 

 

你可能感兴趣的:(python)