最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python實(shí)現(xiàn)的用于搜索文件并進(jìn)行內(nèi)容替換的類實(shí)例

 更新時(shí)間:2015年06月28日 16:21:36   作者:不吃皮蛋  
這篇文章主要介紹了python實(shí)現(xiàn)的用于搜索文件并進(jìn)行內(nèi)容替換的類,涉及Python針對(duì)文件及字符串的相關(guān)操作技巧,需要的朋友可以參考下

本文實(shí)例講述了python實(shí)現(xiàn)的用于搜索文件并進(jìn)行內(nèi)容替換的類。分享給大家供大家參考。具體實(shí)現(xiàn)方法如下:

#!/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
  )

希望本文所述對(duì)大家的Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

  • Python3 虛擬開(kāi)發(fā)環(huán)境搭建過(guò)程(圖文詳解)

    Python3 虛擬開(kāi)發(fā)環(huán)境搭建過(guò)程(圖文詳解)

    這篇文章主要介紹了Python3 虛擬開(kāi)發(fā)環(huán)境搭建過(guò)程,本文通過(guò)圖文實(shí)例代碼相結(jié)合給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-01-01
  • Python做圖像處理及視頻音頻文件分離和合成功能

    Python做圖像處理及視頻音頻文件分離和合成功能

    這篇文章主要介紹了Python做圖像處理及視頻音頻文件分離和合成功能,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-11-11
  • 解決reload(sys)后print失效的問(wèn)題

    解決reload(sys)后print失效的問(wèn)題

    這篇文章主要介紹了解決reload(sys)后print失效的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-04-04
  • 利用Python實(shí)現(xiàn)顏色色值轉(zhuǎn)換的小工具

    利用Python實(shí)現(xiàn)顏色色值轉(zhuǎn)換的小工具

    最近一個(gè)朋友說(shuō)已經(jīng)轉(zhuǎn)用Zeplin很久了。Zeplin的設(shè)計(jì)稿展示頁(yè)面的顏色色值使用十進(jìn)制的 RGB 表示的,在 Android 中的顏色表示大多情況下都需要十六進(jìn)制的 RGB 表示。所以想寫(xiě)個(gè)工作,當(dāng)輸入十進(jìn)制的RGB ,得到十六進(jìn)制的色值,最好可以方便復(fù)制。下面來(lái)一起看看吧。
    2016-10-10
  • Python實(shí)現(xiàn)PDF文字識(shí)別提取并寫(xiě)入CSV文件

    Python實(shí)現(xiàn)PDF文字識(shí)別提取并寫(xiě)入CSV文件

    這篇文章主要是和大家分享一個(gè)Python實(shí)現(xiàn)PDF文字識(shí)別與提取并寫(xiě)入?CSV文件的腳本。文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下
    2022-03-03
  • pywinauto自動(dòng)化測(cè)試使用經(jīng)驗(yàn)

    pywinauto自動(dòng)化測(cè)試使用經(jīng)驗(yàn)

    本文主要介紹了pywinauto自動(dòng)化測(cè)試使用經(jīng)驗(yàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-03-03
  • pandas.DataFrame選取/排除特定行的方法

    pandas.DataFrame選取/排除特定行的方法

    今天小編就為大家分享一篇pandas.DataFrame選取/排除特定行的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-07-07
  • 使用Python編寫(xiě)電腦定時(shí)關(guān)機(jī)小程序

    使用Python編寫(xiě)電腦定時(shí)關(guān)機(jī)小程序

    這篇文章主要為大家詳細(xì)介紹了如何使用Python編寫(xiě)電腦定時(shí)關(guān)機(jī)小程序,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2024-01-01
  • Python編程基礎(chǔ)之函數(shù)和模塊

    Python編程基礎(chǔ)之函數(shù)和模塊

    這篇文章主要為大家介紹了Python函數(shù)和模塊,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助
    2021-12-12
  • 對(duì)python中的try、except、finally 執(zhí)行順序詳解

    對(duì)python中的try、except、finally 執(zhí)行順序詳解

    今天小編就為大家分享一篇對(duì)python中的try、except、finally 執(zhí)行順序詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-02-02

最新評(píng)論

马尔康县| 栖霞市| 莱芜市| 渭源县| 肇东市| 鱼台县| 都江堰市| 吴江市| 崇明县| 巴林右旗| 巢湖市| 青岛市| 建瓯市| 滦南县| 富民县| 萍乡市| 陵川县| 陆川县| 江阴市| 绥滨县| 阿拉善左旗| 禄丰县| 昔阳县| 安泽县| 内江市| 南皮县| 五华县| 城市| 西平县| 开鲁县| 新密市| 汾西县| 荥阳市| 九龙县| 肥乡县| 二连浩特市| 冷水江市| 固原市| 安陆市| 肥乡县| 抚松县|