python标准库实例详解七

发布时间:2020-06-07编辑:脚本学堂
本节是python标准库实例教程的第七节,学习并掌握下python文件与目录模块,以及字符串模块的用法,有需要的朋友参考下。
使用字符串方法替代 string 模块函数
 

复制代码 代码示例:
text = "Monty Python's Flying Circus"
 
print "upper", "=>", text.upper()
print "lower", "=>", text.lower()
print "split", "=>", text.split()
print "join", "=>", "+".join(text.split())
print "replace", "=>", text.replace("Python", "Perl")
print "find", "=>", text.find("Python"), text.find("Perl")
print "count", "=>", text.count("n")
 
upper => MONTY PYTHON'S FLYING CIRCUS
lower => monty python's flying circus
split => ['Monty', "Python's", 'Flying', 'Circus']
join => Monty+Python's+Flying+Circus
replace => Monty Perl's Flying Circus
find => 6 -1
count => 3
 

使用 string 模块将字符串转为数字
 

复制代码 代码示例:
import string
 
print int("4711"),
print string.atoi("4711"),
print string.atoi("11147", 8), # octal 八进制
print string.atoi("1267", 16), # hexadecimal 十六进制
print string.atoi("3mv", 36) # whatever...
 
print string.atoi("4711", 0),
print string.atoi("04711", 0),
print string.atoi("0x4711", 0)
 
print float("4711"),
print string.atof("1"),
print string.atof("1.23e5")
 
4711 4711 4711 4711 4711
4711 2505 18193
4711.0 1.0 123000.0
 

  operator 模块为 Python 提供了一个 "功能性" 的标准操作符接口. 当使用 map 以及 filter 一类的函数的时候, operator 模块中的函数可以替换一些lambda 函式. 而且这些函数在一些喜欢写晦涩代码的程序员中很流行.
使用 operator 模块
 

复制代码 代码示例:
print "add", "=>", reduce(operator.add, sequence)
print "sub", "=>", reduce(operator.sub, sequence)
print "mul", "=>", reduce(operator.mul, sequence)
print "concat", "=>", operator.concat("spam", "egg")
print "repeat", "=>", operator.repeat("spam", 5)
print "getitem", "=>", operator.getitem(sequence, 2)
print "indexOf", "=>", operator.indexOf(sequence, 2)
print "sequenceincludes", "=>", operator.sequenceIncludes(sequence, 3)
 
add => 7
sub => -5
mul => 8
concat => spamegg
repeat => spamspamspamspamspam
 
getitem => 4
indexOf => 1
sequenceIncludes => 0
 

使用 operator 模块检查类型
 

复制代码 代码示例:
import operator
import UserList
 
def dump(data):
    print type(data), "=>",
    if operator.isCallable(data):
        print "CALLABLE",
    if operator.isMappingType(data):
        print "MAPPING",
    if operator.isNumberType(data):
        print "NUMBER",
    if operator.isSequenceType(data):
        print "SEQUENCE",
    print
        
dump(0)
dump("string")
dump("string"[0])
dump([1, 2, 3])
dump((1, 2, 3))
dump({"a": 1})
dump(len) # function 函数
dump(UserList) # module 模块
dump(UserList.UserList) # class 类
dump(UserList.UserList()) # instance 实例
 
<type 'int'> => NUMBER
<type 'string'> => SEQUENCE
<type 'string'> => SEQUENCE
<type 'list'> => SEQUENCE
<type 'tuple'> => SEQUENCE
<type 'dictionary'> => MAPPING
<type 'builtin_function_or_method'> => CALLABLE
<type 'module'> =>
<type 'class'> => CALLABLE
<type 'instance'> => MAPPING NUMBER SEQUENCE
 

  copy 模块包含两个函数, 用来拷贝对象
使用 copy 模块复制对象
 

复制代码 代码示例:
import copy
 
a = [[1],[2],[3]]
b = copy.copy(a)
 
print "before", "=>"
print a
print b
 
# modify original
a[0][0] = 0
a[1] = None
 
print "after", "=>"
print a
print b
 
before =>
[[1], [2], [3]]
[[1], [2], [3]]
after =>
[[0], None, [3]]
[[0], [2], [3]]
 

使用 copy 模块复制集合(Collections)
 

复制代码 代码示例:
import copy
 
a = [[1],[2],[3]]
b = copy.deepcopy(a)
 
print "before", "=>"
print a
print b
 
# modify original
a[0][0] = 0
a[1] = None
 
print "after", "=>"
print a
print b
 
before =>
[[1], [2], [3]]
[[1], [2], [3]]
after =>
[[0], None, [3]]
[[1], [2], [3]]
 

 使用sys模块获得脚本的参数
 

复制代码 代码示例:
import sys
 
print "script name is", sys.argv[0]
 
if len(sys.argv) > 1:
    print "there are", len(sys.argv)-1, "arguments:"
    for arg in sys.argv[1:]:
        print arg
else:
    print "there are no arguments!"
 
script name is sys-argv-example-1.py
there are no arguments!
 

使用sys模块操作模块搜索路径
 

复制代码 代码示例:
import sys
 
print "path has", len(sys.path), "members"
 
# add the sample directory to the path
sys.path.insert(0, "samples")
import sample
 
# nuke the path
sys.path = []
import random # oops!
 
path has 7 members
this is the sample module!
Traceback (innermost last):
  File "sys-path-example-1.py", line 11, in ?
    import random # oops!
ImportError: No module named random
 

使用sys模块查找内建模块
 

复制代码 代码示例:
import sys
 
def dump(module):
    print module, "=>",
    if module in sys.builtin_module_names:
        print "<BUILTIN>"
    else:
        module = _ _import_ _(module)
        print module._ _file_ _
 
dump("os")
dump("sys")
dump("string")
dump("strop")
dump("zlib")
 
os => C:pythonlibos.pyc
sys => <BUILTIN>
string => C:pythonlibstring.pyc
strop => <BUILTIN>
zlib => C:pythonzlib.pyd
 

使用sys模块查找已导入的模块
modules 字典包含所有加载的模块. import 语句在从磁盘导入内容之前会先检查这个字典.
 

复制代码 代码示例:
import sys
 
print sys.modules.keys()
 
['os.path', 'os', 'exceptions', '_ _main_ _', 'ntpath', 'strop', 'nt',
'sys', '_ _builtin_ _', 'site', 'signal', 'UserDict', 'string', 'stat']
 

  getrefcount 函数 返回给定对象的引用记数 - 也就是这个对象使用次数. Python 会跟踪这个值, 当它减少为0的时候, 就销毁这个对象.
使用sys模块获得引用记数
 

复制代码 代码示例:
import sys
 
variable = 1234
 
print sys.getrefcount(0)
print sys.getrefcount(variable)
print sys.getrefcount(None)
 
50
3
192
 

  注意这个值总是比实际的数量大, 因为该函数本身在确定这个值的时候依赖这个对象
使用sys模块获得当前平台
 

复制代码 代码示例:
import sys
 
#
# emulate "import os.path" (sort of)...
 
if sys.platform == "win32":
    import ntpath
    pathmodule = ntpath
elif sys.platform == "mac":
    import macpath
    pathmodule = macpath
else:
    # assume it's a posix platform
    import posixpath
    pathmodule = posixpath
 
print pathmodule
 

  setprofiler 函数允许你配置一个分析函数(profiling function). 这个函数会在每次调用某个函数或方法时被调用(明确或隐含的), 或是遇到异常的时候被调用.
使用sys模块配置分析函数
 

复制代码 代码示例:
import sys
 
def test(n):
    j = 0
    for i in range(n):
        j = j + i
    return n
 
def profiler(frame, event, arg):
    print event, frame.f_code.co_name, frame.f_lineno, "->", arg
 
# profiler is activated on the next call, return, or exception
# 分析函数将在下次函数调用, 返回, 或异常时激活
sys.setprofile(profiler)
 
# profile this function call
# 分析这次函数调用
test(1)
 
# disable profiler
# 禁用分析函数
sys.setprofile(None)
 
# don't profile this call
# 不会分析这次函数调用
test(2)
 
call test 3 -> None
return test 7 -> 1
 

使用sys模块配置单步跟踪函数
 

复制代码 代码示例:
import sys
 
def test(n):
    j = 0
    for i in range(n):
        j = j + i
    return n
 
def tracer(frame, event, arg):
    print event, frame.f_code.co_name, frame.f_lineno, "->", arg
    return tracer
 
# tracer is activated on the next call, return, or exception
# 跟踪器将在下次函数调用, 返回, 或异常时激活
sys.settrace(tracer)
 
# trace this function call
# 跟踪这次函数调用
test(1)
 
# disable tracing
# 禁用跟踪器
sys.settrace(None)
 
# don't trace this call
# 不会跟踪这次函数调用
test(2)
 
call test 3 -> None
line test 3 -> None
line test 4 -> None
line test 5 -> None
line test 5 -> None
line test 6 -> None
line test 5 -> None
line test 7 -> None
return test 7 -> 1