web-dev-qa-db-ja.com

python)での差分の生成と適用

pythonに「すぐに使える」方法で2つのテキストの違いのリストを生成し、この差分を1つのファイルに適用して、後でもう1つのファイルを取得する方法はありますか?

テキストの改訂履歴を保持したいのですが、編集した行が1つしかない場合は、改訂ごとにテキスト全体を保存したくありません。 difflib を見ましたが、一方のテキストを変更してもう一方のテキストを取得するために使用できる、編集された行だけのリストを生成する方法がわかりませんでした。

28
noio

グーグルのdiff-match-patchを見ましたか?どうやらグーグルドキュメントはこのアルゴリズムのセットを使用しています。差分モジュールだけでなくパッチモジュールも含まれているので、古いファイルや差分から最新のファイルを生成できます。

pythonバージョンが含まれています。

http://code.google.com/p/google-diff-match-patch/

26
Density 21.5

Difflib.unified_diffはあなたが欲しいですか?例があります ここ

11
pwdyson

純粋なpython関数を実装して、diffパッチを適用し、入力文字列のいずれかを回復しました。誰かがそれを役立つと思っていることを願っています。解析を使用します nified diff format

import re

_hdr_pat = re.compile("^@@ -(\d+),?(\d+)? \+(\d+),?(\d+)? @@$")

def apply_patch(s,patch,revert=False):
  """
  Apply unified diff patch to string s to recover newer string.
  If revert is True, treat s as the newer string, recover older string.
  """
  s = s.splitlines(True)
  p = patch.splitlines(True)
  t = ''
  i = sl = 0
  (midx,sign) = (1,'+') if not revert else (3,'-')
  while i < len(p) and p[i].startswith(("---","+++")): i += 1 # skip header lines
  while i < len(p):
    m = _hdr_pat.match(p[i])
    if not m: raise Exception("Cannot process diff")
    i += 1
    l = int(m.group(midx))-1 + (m.group(midx+1) == '0')
    t += ''.join(s[sl:l])
    sl = l
    while i < len(p) and p[i][0] != '@':
      if i+1 < len(p) and p[i+1][0] == '\\': line = p[i][:-1]; i += 2
      else: line = p[i]; i += 1
      if len(line) > 0:
        if line[0] == sign or line[0] == ' ': t += line[1:]
        sl += (line[0] != sign)
  t += ''.join(s[sl:])
  return t

ヘッダー行がある場合("--- ...\n","+++ ...\n")それはそれらをスキップします。 diffstroldstrの間の差分を表す統一された差分文字列newstrがある場合:

# recreate `newstr` from `oldstr`+patch
newstr = apply_patch(oldstr, diffstr)
# recreate `oldstr` from `newstr`+patch
oldstr = apply_patch(newstr, diffstr, True)

Pythonでは、difflib(標準ライブラリの一部)を使用して、2つの文字列の統一された差分を生成できます。

import difflib
_no_eol = "\ No newline at end of file"

def make_patch(a,b):
  """
  Get unified string diff between two strings. Trims top two lines.
  Returns empty string if strings are identical.
  """
  diffs = difflib.unified_diff(a.splitlines(True),b.splitlines(True),n=0)
  try: _,_ = next(diffs),next(diffs)
  except StopIteration: pass
  return ''.join([d if d[-1] == '\n' else d+'\n'+_no_eol+'\n' for d in diffs])

UNIXの場合:diff -U0 a.txt b.txt

コードはここでGitHubにあり、ASCIIとランダムなUnicode文字を使用したテストがあります: https://Gist.github.com/noporpoise/16e731849eb1231e8​​6d78f9dfeca3abc

2
Isaac Turner

AFAIKのほとんどのdiffアルゴリズムは、単純な 最長共通部分列 一致を使用して、2つのテキスト間の共通部分を見つけ、残っているものはすべて違いと見なされます。 Pythonでそれを達成するために、独自の動的計画法アルゴリズムをコーディングすることはそれほど難しいことではありません。上記のウィキペディアのページにもアルゴリズムが記載されています。

2
jai

おそらく、 nified_diff を使用して、ファイル内の差分のリストを生成できます。ファイル内の変更されたテキストのみを新しいテキストファイルに書き込んで、後で参照するために使用できます。これは、新しいファイルに違いだけを書き込むのに役立つコードです。これがあなたが求めているものであることを願っています!

diff = difflib.unified_diff(old_file, new_file, lineterm='')
    lines = list(diff)[2:]
    # linesT = list(diff)[0:3]
    print (lines[0])
    added = [lineA for lineA in lines if lineA[0] == '+']


    with open("output.txt", "w") as fh1:
     for line in added:
       fh1.write(line)
    print '+',added
    removed = [lineB for lineB in lines if lineB[0] == '-']
    with open("output.txt", "a") as fh1:
     for line in removed:
       fh1.write(line)
    print '-',removed 

これをコードで使用して、差分出力のみを保存します。

0
Karthik Hegde

pythonソリューションである必要がありますか?
解決策についての私の最初の考えは、バージョン管理システム(Subversion、Gitなど)または標準のdiff/patchユーティリティのいずれかを使用することです。 UNIXシステム、またはWindowsベースのシステムのcygwinの一部です。

0
Simon Callan