Python字串和檔案操作常用函數分析

來源:互聯網
上載者:User
本文執行個體分析了Python字串和檔案操作常用函數。分享給大家供大家參考。具體如下:

# -*- coding: UTF-8 -*-'''Created on 2010-12-27@author: sumory'''import itertoolsdef a_containsAnyOf_b(seq,aset):  '''判斷seq中是否含有aset裡的一個或者多個項    seq可以是字串或者列表    aset應該是字串或者列表'''  for item in itertools.ifilter(aset.__contains__,seq):    return True  return Falsedef a_allIn_b(seq,aset):  '''判斷seq中的所有項是否都在aset裡    seq可以是字串或者列表    aset應該是字串或者列表'''  for item in seq:    if item not in aset:      return False  return Truedef a_containsAll_b(seq,aset):  '''判斷seq是否包含aset裡的所有項    seq可以是字串或者列表    aset應該是字串或者列表         任何一個set對象a,a.difference(b)等價於a-set(b),即返回a中所有不屬於b的元素'''  return not set(aset).difference(seq) import string#產生所有字元的可複用的字串sumory_allchars=string.maketrans('','')def makefilter(keep):  '''返回一個函數,此函數接受一個源字串作為參數\    並返回字串的一個部分拷貝\    此拷貝只包括keep中的字元,keep必須是一個普通的字串\    調用樣本:makefilter('abca ')('abcdefgh ijkal cba')\    在後面的字串中保留前面出現的字元 abc a cba  '''  #按照sumory_allchars規則剔除sumory_allchars字串中的keep裡的字元  #這裡得到keep在sumory_allchars的補集  deletechars=sumory_allchars.translate(sumory_allchars,keep)  #產生並返回需要的過濾函數(作為閉包)  def realdelete(sourseStr):    return sourseStr.translate(sumory_allchars,deletechars)  return realdeletedef list_removesame(list):  '''刪除list中的重複項'''  templist=[]  for c in list:    if c not in templist:      templist.append(c)  return templistdef re_indent(str,numberofspace):  '''  縮排\  將字串str中按分行符號劃分並在每句前加上numberofspace個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包裹的相應值'''  #如果safe為True,那麼字典中沒找到key時不替換  if safe:    def lookup(w):      return dict.get(w,w.join(marker*2))   #w.join(marker*2)用marker包裹w  #如果safe為False,那麼字典中沒找到key時拋異常\  #若將dict[w]換為dict.get(w)則沒找到時返回None  else:    def lookup(w):      return dict[w]  #根據marker切分源字串  splitparts=sourseStr.split(marker)  #取出切分後的奇數項  #因為切分後,列表中源字串中marker包裹的項肯定位於基數部位  #就算是'"first"s is one'這樣的字串也是如此  #分割後的第0項為空白串,第1項為first  splitparts[1::2]=map(lookup,splitparts[1::2])  return ''.join(splitparts)def simply_replace_strby_dict(sourseStr,dict,safe=True):  '''根據dict內容替換sourseStr原串中$標記的子字串\  dict= {'name':'sumory','else':'default'}  $$5 -> $5  $else -> default  ${name}'s method -> sumory's method  '''  style=string.Template(sourseStr)  #如果safe,在dict中找不到的話不會替換,照樣保留原串  if safe:    return style.safe_substitute(dict)  #false,找不到會拋異常  else:    return style.substitute(dict)##################################################def scanner(object,linehandler):  '''用linehandler方法遍曆object的每一項'''  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 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):  '''列出目錄(或者及其子目錄下的檔案)'''  #分割模式到列表  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)

希望本文所述對大家的Python程式設計有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.