我正在阅读python difflib文档。根据difflib.differ输出是:
代码含义 ' - '对序列1唯一的行 '+'行对序列2是唯一的 ''两个序列共有的线 “? '输入序列中不存在行
我也在stackoverflow上阅读这个问题 Python Difflib - How to Get SDiff Sequences with "Change" Op但无法在Sнаđошƒаӽ的答案中添加评论。
我不知道Perl的Sdiff是什么,但我需要调整这个功能:
def sdiffer(s1, s2):
differ = difflib.Differ()
diffs = list(differ.compare(s1, s2))
i = 0
sdiffs = []
length = len(diffs)
while i < length:
line = diffs[i][2:]
if diffs[i].startswith(' '):
sdiffs.append(('u', line))
elif diffs[i].startswith('+ '):
sdiffs.append(('+', line))
elif diffs[i].startswith('- '):
if i+1 < length and diffs[i+1].startswith('? '): # then diffs[i+2] starts with ('+ '), obviously
sdiffs.append(('c', line))
i += 3 if i + 3 < length and diffs[i + 3].startswith('? ') else 2
elif diffs[i+1].startswith('+ ') and i+2<length and diffs[i+2].startswith('? '):
sdiffs.append(('c', line))
i += 2
else:
sdiffs.append(('-', line))
i += 1
return sdiffs
上面的函数我试过,它返回UNCHANGE,ADDED和DELETED的值。 DELETED更复杂,有4种不同的情况:
案例1 :通过插入一些字符来修改该行
- The good bad
+ The good the bad
? ++++
案例2 :通过删除一些字符来修改该行
- The good the bad
? ----
+ The good bad
案例3 :通过删除和插入和/或替换某些字符来修改该行:
- The good the bad and ugly
? ^^ ----
+ The g00d bad and the ugly
? ^^ ++++
案例4 :该行已删除
- The good the bad and the ugly
+ Our ratio is less than 0.75!
我不知道如何在此代码中进行调整
elif diffs[i].startswith('- '):
if i+1 < length and diffs[i+1].startswith('? '): # then diffs[i+2] starts with ('+ '), obviously
sdiffs.append(('c', line))
i += 3 if i + 3 < length and diffs[i + 3].startswith('? ') else 2
elif diffs[i+1].startswith('+ ') and i+2<length and diffs[i+2].startswith('? '):
sdiffs.append(('c', line))
i += 2
else:
sdiffs.append(('-', line))
跳过'?'线。我只想在没有插入新行的情况下追加( - ),如果调用插入新行,则追加(+)。
答案 0 :(得分:0)
我想我已经完成了我想要的PHP Diff输出。
def sdiffer(s1, s2):
differ = difflib.Differ()
diffs = list(differ.compare(s1, s2))
i = 0
sdiffs = []
length = len(diffs)
sequence = 0
while i < length:
line = diffs[i][2:]
if diffs[i].startswith(' '):
sequence +=1
sdiffs.append((sequence,'u', line))
elif diffs[i].startswith('+ '):
sequence +=1
sdiffs.append((sequence,'+', line))
elif diffs[i].startswith('- '):
sequence +=1
sdiffs.append((sequence,'-',diffs[i][2:]))
if i+1 < length and diffs[i+1].startswith('? '):
if diffs[i+3].startswith('?') and i+3 < length : # case 3
sequence +=1
sdiffs.append((sequence,'+',diffs[i+2][2:]))
i+=3
elif diffs[i+2].startswith('?') and i+2 < length: # case 2
sequence +=1
sdiffs.append((sequence,'+',diffs[i+2][2:]))
i+=2
elif diffs[i+1].startswith('+ ') and i+2<length and diffs[i+2].startswith('? '): # case 1
sequence +=1
sdiffs.append((sequence,'+', diffs[i+1][2:]))
i += 2
else: # the line is deleted and inserted new line # case 4
sequence +=1
sdiffs.append((sequence,'+', diffs[i+1][2:]))
i+=1
i += 1
return sdiffs