我希望有更多关于assertEqual不匹配的信息,我正在使用difflib.Differ。但是,当文件很大时,它返回的信息太多了。
如何实现像diff的窗口那样只显示少数上下文行的东西?
@@ -155,6 +155,8 @@ except (ImportError,) as e:
raise
+tst
+
class KeepTextFilter(object):
def __init__(self, regexes = [], f_notify=None):这是我的测试代码:
def get_data():
left, right = [],[]
for num in range(0,10):
lmark = rmark = " "
if not (num % 5):
lmark, rmark = "L", "R"
left.append("%02d%s" % (num, lmark))
right.append("%02d%s" % (num,rmark))
return left, right
from difflib import Differ
differ = Differ()
left, right = get_data()
print(left)
print(right)
output = "\n".join(differ.compare(left, right))
print(output)这就是输出的样子(给定更大的列表,它将输出所有内容)。
['00L', '01 ', '02 ', '03 ', '04 ', '05L', '06 ', '07 ', '08 ', '09 ']
['00R', '01 ', '02 ', '03 ', '04 ', '05R', '06 ', '07 ', '08 ', '09 ']
- 00L
+ 00R
01
02
03
04
- 05L
+ 05R
06
07
08
09 我怎样才能实现拥有一个窗口,比如说1。即
- 00L
+ 00R
01
04
- 05L
+ 05R
06 我正在考虑与一个deque(maxlen=1)一起入侵一些东西,但我想我会问-这似乎是一个明显的要求。我查看了Differ()和compare签名的构造函数,但两者都没有此选项。
发布于 2018-08-15 17:41:19
这就是我想出来的
class DiffFormatter(difflib.Differ):
def _window(self, lines, window=None):
try:
if not window:
return lines
if not isinstance(window, int):
raise TypeError("window has to be an int")
#remember, at most, `window` # of lines
dq = deque(maxlen=window)
cntr = 0
res = []
for line in lines:
if line[0] in ("+","-"):
#reset cntr
cntr = window
while True:
#add `before` context lines
try:
#try if res.extend(dq) works
res.append(dq.popleft())
except (IndexError,) as e:
break
res.append(line)
elif cntr > 0:
#`after` context
#cntr, while > 0 adds line to res
cntr -= 1
res.append(line)
else:
#this line won't be used, unless a later line
#requires it in context.
dq.append(line)
return res
except (Exception,) as e:
raise
def format(self, exp, got, window=None):
try:
exp_ = exp.splitlines()
got_ = got.splitlines()
lines = self.compare(exp_, got_)
if window:
lines2 = self._window(lines, window)
else:
lines2 = list(lines)
msg = "\n".join(lines2)
msg = msg.strip()
if msg and msg[1] != " ":
msg = " %s" % (msg)
return msg
except (Exception,) as e:
raisehttps://stackoverflow.com/questions/51272027
复制相似问题