• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell
您的位置:首页 > 脚本语言 >python > Python字符串和文件操作常用函数分析

Python字符串和文件操作常用函数分析

作者: 字体:[增加 减小] 来源:互联网

通过本文主要向大家介绍了python 字符串函数,python字符串长度函数,字符串替换函数python,python字符串反转函数,python字符串处理函数等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

本文实例分析了Python字符串和文件操作常用函数。分享给大家供大家参考。具体如下:

# -*- coding: UTF-8 -*-
'''
Created on 2010-12-27
@author: sumory
'''
import itertools
def a_containsAnyOf_b(seq,aset):
  '''判断seq中是否含有aset里的一个或者多个项
    seq可以是字符串或者列表
    aset应该是字符串或者列表'''
  for item in itertools.ifilter(aset.__contains__,seq):
    return True
  return False
def a_allIn_b(seq,aset):
  '''判断seq中的所有项是否都在aset里
    seq可以是字符串或者列表
    aset应该是字符串或者列表'''
  for item in seq:
    if item not in aset:
      return False
  return True
def 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 realdelete
def list_removesame(list):
  '''删除list中的重复项'''
  templist=[]
  for c in list:
    if c not in templist:
      templist.append(c)
  return templist
def 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 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)
</div>

希望本文所述对大家的Python程序设计有所帮助。

</div>

您可能想查找下面的文章:

  • python中根据字符串调用函数的实现方法
  • Python中常用操作字符串的函数与方法总结
  • python中常用检测字符串相关函数汇总
  • Python字符串和文件操作常用函数分析
  • Python字符串和文件操作常用函数分析
  • Python内置的字符串处理函数详细整理(覆盖日常所用)
  • Python内置的字符串处理函数详细整理(覆盖日常所用)
  • 浅析python 内置字符串处理函数的使用方法
  • Python内置的字符串处理函数整理
  • Python内置的字符串处理函数整理

相关文章

  • 简单介绍Python中的filter和lambda函数的使用
  • 浅谈Python类的__getitem__和__setitem__特殊方法
  • 编写Python脚本使得web页面上的代码高亮显示
  • python批量提交沙箱问题实例
  • 在Python中用get()方法获取字典键值的教程
  • Python正则表达式教程之一:基础篇
  • Python根据区号生成手机号码的方法
  • Python编写简单的HTML页面合并脚本
  • Django实现图片文字同时提交的方法
  • python基础教程之实现石头剪刀布游戏示例

文章分类

  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell

最近更新的内容

    • 巧用Python装饰器 免去调用父类构造函数的麻烦
    • python自动安装pip
    • Python中使用SAX解析xml实例
    • 使用Python的Twisted框架实现一个简单的服务器
    • TensorFlow实现打印每一层的输出
    • 跟老齐学Python之总结参数的传递
    • python操作MongoDB基础知识
    • Python基于pillow判断图片完整性的方法
    • Python的标准模块包json详解
    • 关于Python面向对象编程的知识点总结

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有