本文實(shí)例分析了Python字符串和文件操作常用函數(shù)。分享給大家供大家參考。具體如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
|
# -*- coding: UTF-8 -*- ''' Created on 2010-12-27 @author: sumory ''' import itertools def a_containsAnyOf_b(seq,aset): '''判斷seq中是否含有aset里的一個(gè)或者多個(gè)項(xiàng) seq可以是字符串或者列表 aset應(yīng)該是字符串或者列表''' for item in itertools.ifilter(aset.__contains__,seq): return True return False def a_allIn_b(seq,aset): '''判斷seq中的所有項(xiàng)是否都在aset里 seq可以是字符串或者列表 aset應(yīng)該是字符串或者列表''' for item in seq: if item not in aset: return False return True def a_containsAll_b(seq,aset): '''判斷seq是否包含aset里的所有項(xiàng) seq可以是字符串或者列表 aset應(yīng)該是字符串或者列表 任何一個(gè)set對(duì)象a,a.difference(b)等價(jià)于a-set(b),即返回a中所有不屬于b的元素''' return not set (aset).difference(seq) import string #生成所有字符的可復(fù)用的字符串 sumory_allchars = string.maketrans(' ',' ') def makefilter(keep): '''返回一個(gè)函數(shù),此函數(shù)接受一個(gè)源字符串作為參數(shù)\ 并返回字符串的一個(gè)部分拷貝\ 此拷貝只包括keep中的字符,keep必須是一個(gè)普通的字符串\ 調(diào)用示例:makefilter('abca ')('abcdefgh ijkal cba')\ 在后面的字符串中保留前面出現(xiàn)的字符 abc a cba ''' #按照sumory_allchars規(guī)則剔除sumory_allchars字符串中的keep里的字符 #這里得到keep在sumory_allchars的補(bǔ)集 deletechars = sumory_allchars.translate(sumory_allchars,keep) #生成并返回需要的過濾函數(shù)(作為閉包) def realdelete(sourseStr): return sourseStr.translate(sumory_allchars,deletechars) return realdelete def list_removesame( list ): '''刪除list中的重復(fù)項(xiàng)''' templist = [] for c in list : if c not in templist: templist.append(c) return templist def re_indent( str ,numberofspace): ''' 縮進(jìn)\ 將字符串str中按換行符劃分并在每句前加上numberofspace個(gè)space\ 再組合成字符串''' spaces = numberofspace * ' ' lines = [spaces + line.strip() for line in str .splitlines()] return '\n' .join(lines) def replace_strby_dict(sourseStr, dict ,marker = '"' ,safe = False ): '''使用字典替換源字符串中的被marker包裹的相應(yīng)值''' #如果safe為True,那么字典中沒找到key時(shí)不替換 if safe: def lookup(w): return dict .get(w,w.join(marker * 2 )) #w.join(marker*2)用marker包裹w #如果safe為False,那么字典中沒找到key時(shí)拋異常\ #若將dict[w]換為dict.get(w)則沒找到時(shí)返回None else : def lookup(w): return dict [w] #根據(jù)marker切分源字符串 splitparts = sourseStr.split(marker) #取出切分后的奇數(shù)項(xiàng) #因?yàn)榍蟹趾螅斜碇性醋址衜arker包裹的項(xiàng)肯定位于基數(shù)部位 #就算是'"first"s is one'這樣的字符串也是如此 #分割后的第0項(xiàng)為空串,第1項(xiàng)為first splitparts[ 1 :: 2 ] = map (lookup,splitparts[ 1 :: 2 ]) return ''.join(splitparts) def simply_replace_strby_dict(sourseStr, dict ,safe = True ): '''根據(jù)dict內(nèi)容替換sourseStr原串中$標(biāo)記的子字符串\ dict= {'name':'sumory','else':'default'} $$5 -> $5 $else -> default ${name}'s method -> sumory's method ''' style = string.Template(sourseStr) #如果safe,在dict中找不到的話不會(huì)替換,照樣保留原串 if safe: return style.safe_substitute( dict ) #false,找不到會(huì)拋異常 else : return style.substitute( dict ) ################################################## def scanner( object ,linehandler): '''用linehandler方法遍歷object的每一項(xiàng)''' for line in object : linehandler(line) def printfilelines(path): '''讀取path路徑下的文件屏逐行打印''' fileobject = open (path, 'r' ) #open不用放到try里 try : for line in fileobject: print (line.rstrip( '\n' )) finally : fileobject.close() def writelisttofile(path,ilist): fileobject = open (path, 'w' ) try : fileobject.writelines(ilist) finally : fileobject.close() import zipfile def listzipfilesinfo(path): z = zipfile.ZipFile(path, 'r' ) try : for filename in z.namelist(): bytes = z.read(filename) print ( 'File:%s Size:%s' % ( unicode (filename, 'cp936' ).decode( 'utf-8' ), len (bytes))) finally : z.close() import os,fnmatch def list_all_files(root,patterns = '*' ,single_level = False ,yield_folders = False ): '''列出目錄(或者及其子目錄下的文件)''' #分割模式到列表 patterns = patterns.split( ';' ) for path,subdirs,files in os.walk(root): if yield_folders: files.extend(subdirs) files.sort() for name in files: for pat in patterns: if fnmatch.fnmatch(name, pat): yield '/' .join( unicode (os.path.join(path,name), 'cp936' ).split( '\\' )) break if single_level: break def swapextensions(root,before,after): if before[: 1 ]! = '.' : before = '.' + before extensionlen = - len (before) if after[: 1 ]! = '.' : after = '.' + after for path,subdirs,files in os.walk(root): for oldfile in files: if oldfile[extensionlen:] = = before: oldfile = os.path.join(path,oldfile) newfile = oldfile[:extensionlen] + after os.rename(oldfile, newfile) |
希望本文所述對(duì)大家的Python程序設(shè)計(jì)有所幫助。