Python string and file operations are commonly used for function analysis
- 2020-05-07 19:55:02
- OfStack
This article analyzes the Python string and file operation functions. Share with you for your reference. The details are as follows:
# -*- coding: UTF-8 -*-
'''
Created on 2010-12-27
@author: sumory
'''
import itertools
def a_containsAnyOf_b(seq,aset):
''' judge seq Whether contains aset In the 1 Two or more terms
seq It could be a string or a list
aset It should be a string or a list '''
for item in itertools.ifilter(aset.__contains__,seq):
return True
return False
def a_allIn_b(seq,aset):
''' judge seq Are all the terms in aset In the
seq It could be a string or a list
aset It should be a string or a list '''
for item in seq:
if item not in aset:
return False
return True
def a_containsAll_b(seq,aset):
''' judge seq Does it include aset All of the terms in
seq It could be a string or a list
aset It should be a string or a list
any 1 a set object a . a.difference(b) Is equivalent to a-set(b), The return a All of them do not belong to b The elements of the '''
return not set(aset).difference(seq)
import string
# Generates a reusable string for all characters
sumory_allchars=string.maketrans('','')
def makefilter(keep):
''' return 1 This function accepts 1 Each source string as an argument \
And returns a string 1 Partial copy \
This copy includes only keep , keep It must be 1 A normal string \
Call example: makefilter('abca ')('abcdefgh ijkal cba')\
Keep the preceding character in the following string abc a cba
'''
# In accordance with the sumory_allchars Rule out sumory_allchars In the string keep In the character
# To get here keep in sumory_allchars The complement of
deletechars=sumory_allchars.translate(sumory_allchars,keep)
# Generate and return the required filter function (as a closure)
def realdelete(sourseStr):
return sourseStr.translate(sumory_allchars,deletechars)
return realdelete
def list_removesame(list):
''' delete list Repeating term in '''
templist=[]
for c in list:
if c not in templist:
templist.append(c)
return templist
def re_indent(str,numberofspace):
'''
The indentation \
The string str Is divided by line breaks and added before each sentence numberofspace a space\
And then combine them into strings '''
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 used in the source string with the dictionary marker The corresponding value of the package '''
# if safe for True So it's not in the dictionary key When don't replace
if safe:
def lookup(w):
return dict.get(w,w.join(marker*2))
#w.join(marker*2) with marker The parcel w
# if safe for False So it's not in the dictionary key When thrown exception \
# If the dict[w] Change for dict.get(w) Return when not found None
else:
def lookup(w):
return dict[w]
# According to the marker Shred the source string
splitparts=sourseStr.split(marker)
# I'm going to take the odd term after the partition
# Because after the shard, the source string in the list marker The item of the package must be in the cardinal number
# even '"first"s is one' The same is true for strings like this
# After partition 0 The item is an empty string 1 Items for first
splitparts[1::2]=map(lookup,splitparts[1::2])
return ''.join(splitparts)
def simply_replace_strby_dict(sourseStr,dict,safe=True):
''' According to the dict Content to replace sourseStr The original string $ A substring of the tag \
dict= {'name':'sumory','else':'default'}
$$5 -> $5
$else -> default
${name}'s method -> sumory's method
'''
style=string.Template(sourseStr)
# if safe In the dict If you can't find the string, you won't replace it
if safe:
return style.safe_substitute(dict)
#false , will throw an exception
else:
return style.substitute(dict)
##################################################
def scanner(object,linehandler):
''' with linehandler Methods through object Each of the 1 item '''
for line in object:
linehandler(line)
def printfilelines(path):
''' read path The file screen under the path is printed line by line '''
fileobject=open(path,'r')#open Don't put try In the
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):
''' List directories (or files in 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:
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)
I hope this article has been helpful to your Python programming.