python基础教程(第二版)

来源:互联网 发布:国产羽绒服 知乎 编辑:程序博客网 时间:2024/05/22 15:50

第十章 自带电池

  1. 导入模块:

    import syssys.path.append('c:/python27')//告诉程序到这里找模块

1.1. 若模块是一个程序,则在导入时只执行一次,后面导入不在执行,修改后可以用reload函数重新导入,这时会重新执行。

#hello2.pydef hello():    print 'Hello,World!'>>>import hello2>>>hello2.hello()hello,world!#hello3.pydef hello():    print "Hello,world!"#A test 测试模块hello()>>>import hello3**Hello,World!**#这不是想要的结果>>>hello3.hello()Hello,World!#解决方法:使用__name__变量#hello4.pydef hello():    print 'Hello,World!'def test():    hello()if __name__ == '__main__':test()>>>import hello4#达到预期效果>>>hello4.hello()

2.把模块放进目录的几种方法:
2.1 把模块放进sys中的path路径中找。

    >>>import sys 

2.2 编辑sys.path,还得在环境变量中实现PYTHONPATH,它包含模块所在的目录。

2.3 命名模块。
包含代码的文件的名字和模块相同。

    • 包含一个命名为__init__.py的文件。
  1. 模块包含的内容:
    dir函数: 列出模块包含内容: dir.copy()
    all变量:从模块导入所有名字包括什么含义: copy.__all__:['Error','copy','deepcopy']
    help:获取帮助
    doc:查看文档 : range.__doc__
    file: 使用源代码: copy.__file__

  2. 标准库
    3.1sys模块

函数 作用 例子 argv 命令行参数,包括脚本名称 exit([arg]) 退出当前程序,可选的参数为给定的返回值或者错误信息 modules 映射模块名字到载入模块的字典 path 查找模块所在目录的目录名列表 platform 类似sunos或win32的平台标识符 stdin 标准输入流 stdout 标准输出流 stderr 标准错误流

3.2 os模块:提供访问多个操作系统服务的功能。

3.3 fileinput模块:读写文件。

函数 作用 input(file[,inplace[,backup]]) 用于遍历多个输入流的行 filename() 返回当前文件的名称 lineno() 返回当前累计的行号 isfirstline() 检查当前行是否是文件的第一行 isstdin() 检查最后一行是否来自sys.stdin nextfile() 关闭当前文件,移动到下一个文件 close() 关闭序列

4. 集合,堆和双端队列
4.1

set(range(10))
set([0,1,2,3,4,5,6,7,8,9])
4.2 集合
集合是可变的不能用作字典中的键。
4.3 堆

函数 作用 heappush(heap,x) 将x入堆 heappop(heap) 将最小的元素弹出 heaoify(heap) 将heap属性强制应用到另一个表 heaprepalce(heap,x) 将堆中最小元素弹出,同时x入栈 nlargest(n,iter) 返回iter中第n大元素 nsmallest(n,iter) 返回iter中第n小元素

4.4 双端队列

  1. time模块
    功能:获得当前时间,操作时间和日期,从字符串读取时间及格式化时间为字符串。
函数 作用 asctime([tuple]) 将时间元组转化为字符串 localtime([secs]) 将秒数转化为日期,以本地时间为准 mktime(tuple) 将时间元组转为本地时间 sleep(secs) 休眠secs秒 strptime(string[,format]) 将字符串解析为时间元组 time() 打印当前时间

4.5 random模块
返回随机数的函数

4.6 shelve模块
存储数据。

4.6.1 使用shelve模块修改临时变量时,要将临时变量绑定到副本上,并且在它被修改后重新存储这个副本。

import shelves = shelv.open('test.dat')s['x'] = ['a','b','c']s['x'].append('d')>>>s['x']['a','b','c']#解决方法,临时变量temp = s['x']temp.append('d')s['x'] = temp>>>s['x']['a','b','c','d']

4.7 re模块
4.7.1
通配符(.):匹配任何字符
转义():对特殊字符转义
字符集([]):[^abc]反转字符,除了abc以外的任意字符。
选择字符或子模式(|):’p(ython|er)’
4.7.2 re模块的一些重要函数

函数 作用 compile(pattern[,flags]) 包含正则表达式的字符串创建模式对象 search(pattern,string[,flags]) 在字符串中寻找模式 match(pattern,string[,flags]) 在字符串的开始处匹配模式 split(pattern,string[,maxsplit=0]) 根据模式的匹配项分割字符串 findall(pattern,string) 列出字符串中模式的而所有匹配项 sub(pat,repl,string[,count=0]) 将字符串中所有pat的匹配用repl替换 escape(string) 将字符串中所有特殊正则表达式字符转义

4.7.3匹配对象和组
group(0):表示整个字符串。
group(m):表示左边有m个左括号的m组

4.7.4贪婪和非贪婪模式
加上(?):是非贪婪的,即最少匹配原则
(.+)(.+?)

#贪婪模式>>>emphasis_pattern = r'\*(.+)\*'>>>re.sub(emphasis_pattern,r'<em>\1</em>','*This* is *it*!')'<em>This* is *it</em>!'#非贪婪模式>>>emphasis_pattern = r'\*(.+?)\*'>>>re.sub(emphasis_pattern,r'<em>\1</em>','*This* is *it*!')'<em>This</em> is <em>it</em>!'

4.7.5 模板系统
模板是通过放入具体值从而得到某种已完成的文件。

#template.pyimport fileinput,refield_pat = re.compile(r'\[(.+?)\]')scope = {}def replacement(match):    code = match.group(1)    try:        return str(eval(code,scope))    except SyntaxError:        exec code in scope        return ''lines = []for line in fileinput.input():    lines.append(line)    text = ''.join(lines)print field_pat.sub(replacement, text)#data.txt[x=2][y=3]The sum of [x] and [y] is [x+y]#运行python template.py data.txt#结果The sum of x and y is 5
阅读全文
0 0