python实现的用于搜索文件并进行内容替换的类实例


Posted in Python onJune 28, 2015

本文实例讲述了python实现的用于搜索文件并进行内容替换的类。分享给大家供大家参考。具体实现方法如下:

#!/usr/bin/python -O
# coding: UTF-8
"""
-replace string in files (recursive)
-display the difference.
v0.2
 - search_string can be a re.compile() object -> use re.sub for replacing
v0.1
 - initial version
  Useable by a small "client" script, e.g.:
-------------------------------------------------------------------------------
#!/usr/bin/python -O
# coding: UTF-8
import sys, re
#sys.path.insert(0,"/path/to/git/repro/") # Please change path
from replace_in_files import SearchAndReplace
SearchAndReplace(
  search_path = "/to/the/files/",
  # e.g.: simple string replace:
  search_string = 'the old string',
  replace_string = 'the new string',
  # e.g.: Regular expression replacing (used re.sub)
  #search_string = re.compile('{% url (.*?) %}'),
  #replace_string = "{% url '\g<1>' %}",
  search_only = True, # Display only the difference
  #search_only = False, # write the new content
  file_filter=("*.py",), # fnmatch-Filter
)
-------------------------------------------------------------------------------
:copyleft: 2009-2011 by Jens Diemer
"""
__author__ = "Jens Diemer"
__license__ = """GNU General Public License v3 or above -
 http://www.opensource.org/licenses/gpl-license.php"""
__url__ = "http://www.jensdiemer.de"
__version__ = "0.2"
import os, re, time, fnmatch, difflib
# FIXME: see http://stackoverflow.com/questions/4730121/cant-get-an-objects-class-name-in-python
RE_TYPE = type(re.compile(""))
class SearchAndReplace(object):
  def __init__(self, search_path, search_string, replace_string,
                    search_only=True, file_filter=("*.*",)):
    self.search_path = search_path
    self.search_string = search_string
    self.replace_string = replace_string
    self.search_only = search_only
    self.file_filter = file_filter
    assert isinstance(self.file_filter, (list, tuple))
    # FIXME: see http://stackoverflow.com/questions/4730121/cant-get-an-objects-class-name-in-python
    self.is_re = isinstance(self.search_string, RE_TYPE)
    print "Search '%s' in [%s]..." % (
      self.search_string, self.search_path
    )
    print "_" * 80
    time_begin = time.time()
    file_count = self.walk()
    print "_" * 80
    print "%s files searched in %0.2fsec." % (
      file_count, (time.time() - time_begin)
    )
  def walk(self):
    file_count = 0
    for root, dirlist, filelist in os.walk(self.search_path):
      if ".svn" in root:
        continue
      for filename in filelist:
        for file_filter in self.file_filter:
          if fnmatch.fnmatch(filename, file_filter):
            self.search_file(os.path.join(root, filename))
            file_count += 1
    return file_count
  def search_file(self, filepath):
    f = file(filepath, "r")
    old_content = f.read()
    f.close()
    if self.is_re or self.search_string in old_content:
      new_content = self.replace_content(old_content, filepath)
      if self.is_re and new_content == old_content:
        return
      print filepath
      self.display_plaintext_diff(old_content, new_content)
  def replace_content(self, old_content, filepath):
    if self.is_re:
      new_content = self.search_string.sub(self.replace_string, old_content)
      if new_content == old_content:
        return old_content
    else:
      new_content = old_content.replace(
        self.search_string, self.replace_string
      )
    if self.search_only != False:
      return new_content
    print "Write new content into %s..." % filepath,
    try:
      f = file(filepath, "w")
      f.write(new_content)
      f.close()
    except IOError, msg:
      print "Error:", msg
    else:
      print "OK"
    print
    return new_content
  def display_plaintext_diff(self, content1, content2):
    """
    Display a diff.
    """
    content1 = content1.splitlines()
    content2 = content2.splitlines()
    diff = difflib.Differ().compare(content1, content2)
    def is_diff_line(line):
      for char in ("-", "+", "?"):
        if line.startswith(char):
          return True
      return False
    print "line | text\n-------------------------------------------"
    old_line = ""
    in_block = False
    old_lineno = lineno = 0
    for line in diff:
      if line.startswith(" ") or line.startswith("+"):
        lineno += 1
      if old_lineno == lineno:
        display_line = "%4s | %s" % ("", line.rstrip())
      else:
        display_line = "%4s | %s" % (lineno, line.rstrip())
      if is_diff_line(line):
        if not in_block:
          print "..."
          # Display previous line
          print old_line
          in_block = True
        print display_line
      else:
        if in_block:
          # Display the next line aber a diff-block
          print display_line
        in_block = False
      old_line = display_line
      old_lineno = lineno
    print "..."
if __name__ == "__main__":
  SearchAndReplace(
    search_path=".",
    # e.g.: simple string replace:
    search_string='the old string',
    replace_string='the new string',
    # e.g.: Regular expression replacing (used re.sub)
    #search_string  = re.compile('{% url (.*?) %}'),
    #replace_string = "{% url '\g<1>' %}",
    search_only=True, # Display only the difference
#    search_only   = False, # write the new content
    file_filter=("*.py",), # fnmatch-Filter
  )

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

Python 相关文章推荐
Python对象的深拷贝和浅拷贝详解
Aug 25 Python
Python实现把xml或xsl转换为html格式
Apr 08 Python
简单介绍Python中的RSS处理
Apr 13 Python
在类Unix系统上开始Python3编程入门
Aug 20 Python
基于Django filter中用contains和icontains的区别(详解)
Dec 12 Python
DataFrame 将某列数据转为数组的方法
Apr 13 Python
Python简单基础小程序的实例代码
Apr 28 Python
pytorch 实现打印模型的参数值
Dec 30 Python
python3将变量写入SQL语句的实现方式
Mar 02 Python
python调用百度AI接口实现人流量统计
Feb 03 Python
OpenCV-Python直方图均衡化实现图像去雾
Jun 07 Python
利用For循环遍历Python字典的三种方法实例
Mar 25 Python
python实现简单ftp客户端的方法
Jun 28 #Python
基于进程内通讯的python聊天室实现方法
Jun 28 #Python
python实现的简单RPG游戏流程实例
Jun 28 #Python
python实现自动登录人人网并采集信息的方法
Jun 28 #Python
Python实现将绝对URL替换成相对URL的方法
Jun 28 #Python
python实现将html表格转换成CSV文件的方法
Jun 28 #Python
python实现根据主机名字获得所有ip地址的方法
Jun 28 #Python
You might like
PHP使用DOMDocument类生成HTML实例(包含常见标签元素)
2014/06/25 PHP
php获取url参数方法总结
2014/11/13 PHP
彻底删除thinkphp3.1案例blog标签的方法
2014/12/05 PHP
php实现面包屑导航例子分享
2015/12/19 PHP
javascript 禁止复制网页
2009/06/11 Javascript
Jquery提交表单 Form.js官方插件介绍
2012/03/01 Javascript
jquery DIV撑大让滚动条滚到最底部代码
2013/06/06 Javascript
js实现div的切换特效上一个下一个
2014/02/11 Javascript
angularJS与bootstrap结合实现动态加载弹出提示内容
2015/10/16 Javascript
基于JS代码实现导航条弹出式悬浮菜单
2016/06/17 Javascript
Javascript获取图片原始宽度和高度的方法详解
2016/09/20 Javascript
基于Javascript倒计时效果
2016/12/22 Javascript
Vue v2.5 调整和更新不完全问题
2017/10/24 Javascript
vue.js $refs和$emit 父子组件交互的方法
2017/12/20 Javascript
angularJs-$http实现百度搜索时的动态下拉框示例
2018/02/27 Javascript
Vuex实现计数器以及列表展示效果
2018/03/10 Javascript
微信小程序 生成携带参数的二维码
2019/10/23 Javascript
Vue使用Three.js加载glTF模型的方法详解
2020/06/14 Javascript
[06:15]2016国际邀请赛中国区预选赛单车采访:我顶WINGS
2016/06/27 DOTA
Python采用Django开发自己的博客系统
2020/09/29 Python
python 中random模块的常用方法总结
2017/07/08 Python
python利用smtplib实现QQ邮箱发送邮件
2020/05/20 Python
在python 中实现运行多条shell命令
2019/01/07 Python
python小程序基于Jupyter实现天气查询的方法
2020/03/27 Python
Windows下Anaconda和PyCharm的安装与使用详解
2020/04/23 Python
Jupyter notebook如何实现指定浏览器打开
2020/05/13 Python
html5新特性与用法大全
2018/09/13 HTML / CSS
canvas实现图片马赛克的示例代码
2018/03/26 HTML / CSS
美国真皮手袋品牌:GiGi New York
2017/03/10 全球购物
运动鞋、街头服装、手表和手袋的实时市场:StockX
2020/11/25 全球购物
运动会四百米广播稿
2014/01/19 职场文书
光棍节联谊晚会活动策划书
2014/10/10 职场文书
党员教师群众路线思想汇报范文
2014/10/28 职场文书
Java 数组内置函数toArray详解
2021/06/28 Java/Android
python实现剪贴板的操作
2021/07/01 Python
Spring this调用当前类方法无法拦截的示例代码
2022/03/20 Java/Android