python中的diff有什么作用_在python中生成和应用diff

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")

diffstr

oldstr

newstr

# recreate `newstr` from `oldstr`+patch

newstr = apply_patch(oldstr, diffstr)

# recreate `oldstr` from `newstr`+patch

oldstr = apply_patch(newstr, diffstr, True)

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])

diff -U0 a.txt b.txt

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值