python基础教程学习笔记十

第四章   

模块

引用外部模块

Import math

Math.sin(0)

 

自定义模块的导入

#hello.py 文件的保存位置是D:\workspace_python

Print(‘hello world!’)

#添加到环境变量中

Import

Sys.path.append(‘D:\workspace_python’)

 

>>>import hello

Hello world!

如果再次调用,就不会输出打印语句

 

在模块中定义函数

#hello2.py

Def hello():

Print(‘hello world’)

 

>>>Import hello2

>>>Hello2.hello()

Hello world!

 

  在模块中添加测试代码

#hello4.py

Def hello():

Print(‘hello world’)

Def test():

Hello()

#只有它作为主程序运行时,测试方法才会被执行

If __name__==’__main__’:test()

 

 

让模块可用;

1 将模块放到正确的位置

 #输出环境变量

>>> import sys,pprint

>>> pprint.pprint(sys.path)

['',

 'D:\\Python32\\Lib\\idlelib',

 'D:\\Python32',

 'C:\\windows\\system32\\python32.zip',

 'D:\\Python32\\DLLs',

 'D:\\Python32\\lib',

#最佳路径

 'D:\\Python32\\lib\\site-packages',

 'D:\\Python32\\lib\\site-packages\\wx-3.0-msw']

 

 

2 告诉解释器到哪里去找

 PYTHONPATH中添加模块所在的目录

 

3 模块的命名

 是以.py为扩展名,windows中也可以使用pyw为扩展名

 

包名/模块名.py

 

探究模块

#查看模块中包含的内容:

>>>import copy

 [n for n in dir(copy) if not n.startswith('_')]

['Error', 'PyStringMap', 'builtins', 'copy', 'deepcopy', 'dispatch_table', 'error', 'name', 't', 'weakref']

 

#查看模块的公有接口:

>>> copy.__all__

['Error', 'copy', 'deepcopy']

 

#使用help来取得帮助信息

>>> help(copy.copy)

Help on function copy in module copy:

 

copy(x)

    Shallow copy operation on arbitrary Python objects.

    

    See the module's __doc__ string for more info.

 

#查看函数的文档信息

>>> print(range.__doc__)

range([start,] stop[, step]) -> range object

 

Returns a virtual sequence of numbers from start to stop by step.

 

#查看函数源码的存放位置

>>> print(copy.__file__)

D:\Python32\lib\copy.py

 

标准库

1 sys  访问与python解释器有联系的变量和函数

Argv

Exit([argv])

Modules

Path

Platform

Stdin

Stdout

Stderr

 

2 os 访问多个操作系统的功能

Environ

System(command)

Sep

Pathsep

Linesep

Urandom(n)

 

3 fileinput 遍历文本文件中的所有行

Input

Filename()

Lineno()

Filelineno()

Isfirstline()

Isstdin()

Nextfile()

Close()

 

 

集合 堆和双端队列

1  集合 set

>>> set(range(10))

{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

 

#无重复,检查成员资格

>>> set([0,1,2,3,4,5,0,1,2,3,4,5])

{0, 1, 2, 3, 4, 5}

 

#求并集和交集,对整数进行位操作

>>> a=set([1,2,3])

>>> b=set([2,3,4])

>>> a.union(b)

{1, 2, 3, 4}

>>> a|b

{1, 2, 3, 4}

 

Set 的常用方法

Add

Remove

Issubset

Issuperset

Intersection

Difference

Symmetric_dirrerence()

copy

 

#集合是可变的不能用作字典的键

 

2 heap

#常用的几个函数

Heappush #x入堆

Heappop #最小元素弹出

Heapify #

Heapreplace(heap,x)  #将最小的元素弹出,x放入

Mlargest(n,iter)  #n个大小元素

Nsmallest(n,iter)  #n个小的元素

 

 

3 双端队列 deque

#在需要按照元素增加的顺序来移除元素时非常重要

>>> from collections import deque

>>> q=deque(range(5))

>>> q.append(5)

>>> q.appendleft(6)

>>> q

deque([6, 0, 1, 2, 3, 4, 5])

>>> q.pop()

5

>>> q.popleft()

6

>>> q.rotate(3)

>>> q

deque([2, 3, 4, 0, 1])

>>> q.rotate(-1)

>>> q

deque([3, 4, 0, 1, 2])

 

 

Time

取得当前时间,

操作时间和日期

从字符串读取时间

格式化时间字符串

 

#常用函数

Asctime   #时间元组转字符串

Localtime  #秒数转为时间元组

Mktime  # 时间元组转为本地时间

Sleep    #休眠

Strptime #字符串解析为时间元组

Time  #当前时间

 

 

Random  返加随机数

#常用函数

Rondom  #返加随查数

Getrandbits(n)  #返回长整型随机数

Uiform(a,b)  #返回随机实数

Randrange([start],stop,[step])  #

Choice(sep)  #从序列中返回随机数

Shuffle(seq[,random])  #原地指定序列

Sample(seq,n)  # 从序列中返回n个独立的随机数

 

Shelve 简单的存储方案

#简单的数据库应用程序

#database.py

import sys, shelve

 

def store_person(db):

    '''

        query user for data and store it in the shelf object

    '''

    pid=input('Enter unique ID number: ')

    person={}

    person['name']=input('Enter name: ')

    person['age']=input('Enter age: ')

    person['phone']=input('Enter phone number: ')

 

    db[pid]=person

 

def lookup_person(db):

    '''

        query user for ID and desired field. and fetch the corresponding data form

        the shelf object

    '''

 

    pid=input('Enter ID number: ')

    field=input('what would you like to know?(name,age,phone)')

    field=field.strip().lower()

    print(field.capitalize()+':',db[pid][field])

 

def print_help():

    print('The available commands are: ')

    print('store  : stores information about a persion')

    print('lookup : looks up a persion from ID number')

    print('quit   : save changes and exit')

    print('?      : prints this message')

 

def enter_command():

    cmd=input('Enter command (? for help): ')

    cmd=cmd.strip().lower()

    return cmd

 

def main():

    #打开数据文件

    database=shelve.open('c:\\database.dat')

    try:

        while True:

            cmd=enter_command()

            if cmd=='store':

                store_person(database)

            elif cmd=='lookup':

                lookup_person(database)

            elif cmd=='?':

                print_help()

            elif cmd=='quit':

                return

    finally:

        database.close()

if __name__=='__main__':main()

    

    

 

 

测试结果如下:>>>

Enter command (? for help): ?

The available commands are:

store  : stores information about a persion

lookup : looks up a persion from ID number

quit   : save changes and exit

?      : prints this message

Enter command (? for help): store

Enter unique ID number: 001

Enter name: retacn

Enter age: 32

Enter phone number: 18816179937

Enter command (? for help): lookup

Enter ID number: 001

what would you like to know?(name,age,phone)name

Name: retacn

Enter command (? for help): lookup

Enter ID number: 001

what would you like to know?(name,age,phone)phone

Phone: 18816179937

Enter command (? for help): quit

 

 

 

Re 对正则表达式的支持

通配符 (.)单个字符

 

对特殊字符进行转议(\\)

 

字符集

范围[a-z]

[a-zA-Z0-9]

  [^abc]除了abc外的任意字符

 

  选择符和子模式

管道符号(|)  python|perl

子模式()  p(ython|erl)

 

可选项和重复子模式

可选项()?  子模式后加门号

R’htt://)?(www\.)?python\.org’

重复子模式

(pattern)*  #重复0次或多次

(pattern)+    #重复一次或多次

(patern){m,n}  #重复m-n

 

字符串的开始和结尾

^开始

$结束

 

Re模块的内容

常用函数:

Compile(pattern[,flags])  #根据正则表达式的字符串创建模式对象

Search(parth,string[,flags])  #在字符串中寻找模式

Match(pattern,string[,flags])  #在字符串开始处匹配对象

Split(pattern,string[,maxsplit=0]) #根据模式的配匹配项来分割字符串

Findall(pattern,string) #列出字符串中模式的所有匹配项

Sub(pat,repl,string[,count=0]) #将字符串中所有pat的匹配项用repl替换

Escap(string) #将字符串中所有特殊正则表达式字符转义

 

配匹对象和组

组就是放置在圆括号内的子模式

示例代码如下:

There  (was a (wee) (cooper)) who (lived in fyfe)

0 There  (was a (wee) (cooper)) who (lived in fyfe)

1 was a (wee) (cooper)

2 wee

3 cooper

4 lived in fyfe

 

Re中匹配对象的重要方法

Group([group1],...)  #给定子模式的匹配项

Start([group]) # 匹配项的开始伴位置

End([group]) #匹配项的结束位置

Span([group]) #返回一个组的开始和结束位置

 

找出email的发信人

 

 

 

一个简单的模板

# templates.py

 

import fileinput, re

 

# Matches fields enclosed in square brackets:

field_pat = re.compile(r'\[(.+?)\]')

 

 

# We'll collect variables in this:

scope = {}

 

# This is used in re.sub:

def replacement(match):

    code = match.group(1)

    try:

        # If the field can be evaluated, return it:

        return str(eval(code, scope))

    except SyntaxError:

        # Otherwise, execute the assignment in the same scope...

        exec code in scope

        # ...and return an empty string:

        return ''

 

# Get all the text as a single string:

# (There are other ways of doing this; see Chapter 11)

lines = []

for line in fileinput.input():

    lines.append(line)

text = ''.join(lines)

 

# Substitute all the occurrences of the field pattern:

print field_pat.sub(replacement, text)

转载于:https://www.cnblogs.com/retacn-yue/p/6194201.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值