検索
ホームページバックエンド開発Python チュートリアルpython实现的用于搜索文件并进行内容替换的类实例

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

Jun 10, 2016 pm 03:10 PM
pythonコンテンツの置き換えファイル検索親切

本文实例讲述了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 ("-", "+", "&#63;"):
        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 (.*&#63;) %}'),
    #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程序设计有所帮助。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
Python vs. C:重要な違​​いを理解しますPython vs. C:重要な違​​いを理解しますApr 21, 2025 am 12:18 AM

PythonとCにはそれぞれ独自の利点があり、選択はプロジェクトの要件に基づいている必要があります。 1)Pythonは、簡潔な構文と動的タイピングのため、迅速な開発とデータ処理に適しています。 2)Cは、静的なタイピングと手動メモリ管理により、高性能およびシステムプログラミングに適しています。

Python vs. C:プロジェクトのためにどの言語を選択しますか?Python vs. C:プロジェクトのためにどの言語を選択しますか?Apr 21, 2025 am 12:17 AM

PythonまたはCの選択は、プロジェクトの要件に依存します。1)迅速な開発、データ処理、およびプロトタイプ設計が必要な場合は、Pythonを選択します。 2)高性能、低レイテンシ、および緊密なハードウェアコントロールが必要な場合は、Cを選択します。

Pythonの目標に到達する:毎日2時間のパワーPythonの目標に到達する:毎日2時間のパワーApr 20, 2025 am 12:21 AM

毎日2時間のPython学習を投資することで、プログラミングスキルを効果的に改善できます。 1.新しい知識を学ぶ:ドキュメントを読むか、チュートリアルを見る。 2。練習:コードと完全な演習を書きます。 3。レビュー:学んだコンテンツを統合します。 4。プロジェクトの実践:実際のプロジェクトで学んだことを適用します。このような構造化された学習計画は、Pythonを体系的にマスターし、キャリア目標を達成するのに役立ちます。

2時間の最大化:効果的なPython学習戦略2時間の最大化:効果的なPython学習戦略Apr 20, 2025 am 12:20 AM

2時間以内にPythonを効率的に学習する方法は次のとおりです。1。基本的な知識を確認し、Pythonのインストールと基本的な構文に精通していることを確認します。 2。変数、リスト、関数など、Pythonのコア概念を理解します。 3.例を使用して、基本的および高度な使用をマスターします。 4.一般的なエラーとデバッグテクニックを学習します。 5.リストの概念を使用したり、PEP8スタイルガイドに従ったりするなど、パフォーマンスの最適化とベストプラクティスを適用します。

PythonとCのどちらかを選択:あなたに適した言語PythonとCのどちらかを選択:あなたに適した言語Apr 20, 2025 am 12:20 AM

Pythonは初心者やデータサイエンスに適しており、Cはシステムプログラミングとゲーム開発に適しています。 1. Pythonはシンプルで使いやすく、データサイエンスやWeb開発に適しています。 2.Cは、ゲーム開発とシステムプログラミングに適した、高性能と制御を提供します。選択は、プロジェクトのニーズと個人的な関心に基づいている必要があります。

Python vs. C:プログラミング言語の比較分析Python vs. C:プログラミング言語の比較分析Apr 20, 2025 am 12:14 AM

Pythonはデータサイエンスと迅速な発展により適していますが、Cは高性能およびシステムプログラミングにより適しています。 1. Python構文は簡潔で学習しやすく、データ処理と科学的コンピューティングに適しています。 2.Cには複雑な構文がありますが、優れたパフォーマンスがあり、ゲーム開発とシステムプログラミングでよく使用されます。

1日2時間:Python学習の可能性1日2時間:Python学習の可能性Apr 20, 2025 am 12:14 AM

Pythonを学ぶために1日2時間投資することは可能です。 1.新しい知識を学ぶ:リストや辞書など、1時間で新しい概念を学びます。 2。練習と練習:1時間を使用して、小さなプログラムを書くなどのプログラミング演習を実行します。合理的な計画と忍耐力を通じて、Pythonのコアコンセプトを短時間で習得できます。

Python vs. C:曲線と使いやすさの学習Python vs. C:曲線と使いやすさの学習Apr 19, 2025 am 12:20 AM

Pythonは学習と使用が簡単ですが、Cはより強力ですが複雑です。 1。Python構文は簡潔で初心者に適しています。動的なタイピングと自動メモリ管理により、使いやすくなりますが、ランタイムエラーを引き起こす可能性があります。 2.Cは、高性能アプリケーションに適した低レベルの制御と高度な機能を提供しますが、学習しきい値が高く、手動メモリとタイプの安全管理が必要です。

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser は、オンライン試験を安全に受験するための安全なブラウザ環境です。このソフトウェアは、あらゆるコンピュータを安全なワークステーションに変えます。あらゆるユーティリティへのアクセスを制御し、学生が無許可のリソースを使用するのを防ぎます。

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。

SublimeText3 Linux 新バージョン

SublimeText3 Linux 新バージョン

SublimeText3 Linux 最新バージョン