Common Function Analysis for Python string and file operations,
This document analyzes common functions for Python string and file operations. Share it with you for your reference. The details are as follows:
#-*-Coding: UTF-8-*-''' Created on 2010-12-27 @ author: sumory ''' import itertoolsdef a_containsAnyOf_ B (seq, aset ): ''' determine whether seq contains one or more aset seq items, which can be strings or the list aset should be strings or the list ''' for item in itertools. ifilter (aset. _ contains __, seq): return True return Falsedef a_allIn_ B (seq, aset ): ''' determines whether all items in seq are in aset. seq can be a string or the list aset should be a string or list ''' for item in seq: if item not in aset: return False return Truedef a_co NtainsAll_ B (seq, aset): ''' determines whether seq contains all the items in aset. seq can be a string or list. aset should be a string or list any set object a,. difference (B) is equivalent to a-set (B), that is, all elements of a that do not belong to B '''return not set (aset) are returned ). difference (seq) import string # generate reusable strings of all characters sumory_allchars = string. maketrans ('','') def makefilter (keep): ''' a function is returned, this function accepts a source string as the parameter \ and returns a partial copy of the string \ This copy only contains the characters in the keep. The keep must be a common string \ call example: makefilter ('abca') ('abcdefgh ijkal CBA ') \ keep the character abc A CBA ''' # Remove the characters in the keep in the sumory_allchars string according to the sumory_allchars rule # Here we get the supplement set deletechars = sumory_allchars.translate (sumory_allchars, keep) of the keep string) # generate and return the required filter function (as a closure) def realdelete (sourseStr): return sourseStr. translate (sumory_allchars, deletechars) return realdeletedef list_removesame (list): ''' Delete repeated items in the list ''' templist = [] for c in list: if c not in templist: templist. append (c) return templistde F re_indent (str, numberofspace ): '''indent \ divide string 'str' by line break and add numberofspace space before each sentence \ and then combine the string '''spaces = numberofspace * ''' lines = [spaces + line. strip () for line in str. splitlines ()] return '\ n '. join (lines) def replace_strby_dict (sourseStr, dict, marker = '"', safe = False ): ''' replace the corresponding value of the marker package in the source string with the dictionary ''' # if safe is True, if the key is not found in the dictionary, if safe: def lookup (w): return dict. get (w, w. join (marker * 2) # w. join (marker * 2) with m Arker package w # If safe is False, an exception is thrown if the key is not found in the dictionary \ # If dict [w] is changed to dict. if get (w) is not found, None else: def lookup (w): return dict [w] # split the source string splitparts = sourseStr according to marker. split (marker) # retrieve the odd number of items after splitting # Because after splitting, the items of the marker package in the source string in the list must be in the base position # this is true for strings like '"first" s is one' # The 0th items after the split are empty strings, the first splitparts [1: 2] = map (lookup, splitparts [1: 2]) return ''. join (splitparts) def simply_replace_strby_dict (sourseStr, dict, safe = True ): ''' Replace the $-marked substring \ dict = {'name': 'sumory ', 'else' in the original sourseStr string ': 'default'} $5-> $5 $ else-> default $ {name}'s method-> sumory's method ''' style = string. template (sourseStr) # if it is safe, it will not be replaced if it cannot be found in dict, so the original string if safe: return style is retained. safe_substitute (dict) # false. If no value is found, an else: return style exception is thrown. substitute (dict) ######################################## ########## def evaluate (object, linehandler ): ''' Each ''' for line in object: linehandler (line) def printfilelines (path ): '''fileobject = open (path, 'R') # open does not need to be put in 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 zipfiledef 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, fnmatchdef list_all_files (root, patterns = '*', single_level = False, yield_folders = False): ''' list directories (or files in its subdirectories) ''' # split mode to list 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: breakdef 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)
I hope this article will help you with Python programming.