def __init__(self, source, proposal):
proposal = htmlescape(proposal)
differ = Differ()
self.diff = list(differ.compare(source.splitlines(1),
proposal.splitlines(1)))
python类Differ()的实例源码
def contentDiff( f1, f2 ) :
if 'text' in enabledModes :
differ = difflib.Differ()
f1_lines = f1['content'].decode('base64').splitlines()
f2_lines = f2['content'].decode('base64').splitlines()
diff = differ.compare( f1_lines, f2_lines )
__logger.info( '\n'.join( diff ) )
def test_added_tab_hint(self):
# Check fix for bug #1488943
diff = list(difflib.Differ().compare(["\tI am a buggy"],["\t\tI am a bug"]))
self.assertEqual("- \tI am a buggy", diff[0])
self.assertEqual("? --\n", diff[1])
self.assertEqual("+ \t\tI am a bug", diff[2])
self.assertEqual("? +\n", diff[3])
def __init__(self, source, proposal):
proposal = htmlescape(proposal)
differ = Differ()
self.diff = list(differ.compare(source.splitlines(1),
proposal.splitlines(1)))
def load(self, filename):
"""
Load the parameters for this network from disk.
:param filename: Load the parameters of this network from a pickle file at the named path. If this name ends in
".gz" then the input will automatically be gunzipped; otherwise the input will be treated as a "raw" pickle.
:return: None
"""
if filename is None:
return
opener = gzip.open if filename.lower().endswith('.gz') else open
handle = opener(filename, 'rb')
saved = cPickle.load(handle)
handle.close()
if saved['network'] != self.__str__():
print "Possibly not matching network configuration!"
differences = list(difflib.Differ().compare(saved['network'].splitlines(), self.__str__().splitlines()))
print "Differences are:"
print "\n".join(differences)
for layer in self.layers:
if (len(layer.params) + len(layer.params_nontrained)) != len(saved['{}-values'.format(layer.layerNum)]):
print "Warning: Layer parameters for layer {} do not match. Trying to fit on shape!".format(layer.layerNum)
n_assigned = 0
for p in layer.params + layer.params_nontrained:
for v in saved['{}-values'.format(layer.layerNum)]:
if p.get_value().shape == v.shape:
p.set_value(v)
n_assigned += 1
if n_assigned != (len(layer.params) + len(layer.params_nontrained)):
raise ImportError("Could not load all necessary variables!")
else:
print "Found fitting parameters!"
else:
for p, v in zip(layer.params + layer.params_nontrained, saved['{}-values'.format(layer.layerNum)]):
if p.get_value().shape == v.shape:
p.set_value(v)
else:
print "WARNING: Skipping parameter for {}! Shape {} does not fit {}.".format(p.name, p.get_value().shape, v.shape)
print 'Loaded model parameters from {}'.format(filename)
def c(s, md, testcase, **kw):
print('\n\n%s\n' % ('=' * 40))
print('Testcase: %s' % testcase)
print('\n\n%s\n' % ('=' * 40))
md = dedent(md)
print('source (spaces as dots):')
print(md.replace(' ', '.'))
mdr, f = mdvl.main(md, no_print=True, **kw)
print('result:')
print(mdr)
if inspect:
return
fn = pth + '/tests/results/' + testcase
if record:
print ('recording %s' % testcase)
with open(fn, 'w') as fd:
fd.write(mdr)
return
with open(fn) as fd:
exp = fd.read()
if exp == mdr:
return
import difflib
d = difflib.Differ()
diff = d.compare(exp.splitlines(), mdr.splitlines())
print ('\n'.join(diff))
raise Exception('compare failed')
def test_added_tab_hint(self):
# Check fix for bug #1488943
diff = list(difflib.Differ().compare(["\tI am a buggy"],["\t\tI am a bug"]))
self.assertEqual("- \tI am a buggy", diff[0])
self.assertEqual("? --\n", diff[1])
self.assertEqual("+ \t\tI am a bug", diff[2])
self.assertEqual("? +\n", diff[3])
def test_added_tab_hint(self):
# Check fix for bug #1488943
diff = list(difflib.Differ().compare(["\tI am a buggy"],["\t\tI am a bug"]))
self.assertEqual("- \tI am a buggy", diff[0])
self.assertEqual("? --\n", diff[1])
self.assertEqual("+ \t\tI am a bug", diff[2])
self.assertEqual("? +\n", diff[3])
def test_added_tab_hint(self):
# Check fix for bug #1488943
diff = list(difflib.Differ().compare(["\tI am a buggy"],["\t\tI am a bug"]))
self.assertEqual("- \tI am a buggy", diff[0])
self.assertEqual("? --\n", diff[1])
self.assertEqual("+ \t\tI am a bug", diff[2])
self.assertEqual("? +\n", diff[3])
def simple_merge(txt1, txt2):
"""Merges two texts"""
differ = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)
diff = differ.compare(txt1.splitlines(1), txt2.splitlines(1))
content = "".join([l[2:] for l in diff])
return content
def run(bot, sess):
subs = sess.query(SiteSub).all()
for sub in subs: # type: SiteSub
async with aiohttp.ClientSession() as session:
try:
async with session.get(sub.url) as res:
new_body: str = await res.text()
if sub.body != new_body:
old_body_lines = sub.body.splitlines(keepends=True)
new_body_lines = new_body.splitlines(keepends=True)
d = Differ()
diff = [
SPACE_RE.sub(' ', x).rstrip() for x in d.compare(
old_body_lines,
new_body_lines
)
if x[0] not in [' ', '?']
]
await bot.say(
sub.user,
'`{}` ?? ??? ?????!\n```\n{}\n```'.format(
sub.url,
'\n'.join(diff),
)
)
sub.body = new_body
with sess.begin():
sess.add(sub)
except aiohttp.client_exceptions.ClientConnectorError:
await bot.say(
sub.user,
f'`{sub.url}` ? ??? ? ???!'
)
def get_diff(a, b):
import difflib
a, b = a.split('\n'), b.split('\n')
diff = difflib.Differ().compare(a, b)
return '\n'.join(diff)
def _get_diff(a, b):
a, b = a.split('\n'), b.split('\n')
diff = difflib.Differ().compare(a, b)
return '\n'.join(diff)
def _set_diffs(self):
differ = difflib.Differ()
self.lines = []
lineno = 0
for line in differ.compare(self.old.splitlines(True),
self.new.splitlines(True)):
if line.startswith(' '):
lineno += 1
elif line.startswith('-'):
lineno += 1
self.lines.append(lineno)
def test_added_tab_hint(self):
# Check fix for bug #1488943
diff = list(difflib.Differ().compare(["\tI am a buggy"],["\t\tI am a bug"]))
self.assertEqual("- \tI am a buggy", diff[0])
self.assertEqual("? --\n", diff[1])
self.assertEqual("+ \t\tI am a bug", diff[2])
self.assertEqual("? +\n", diff[3])
def highlight_changes(s1, s2):
"""Highlight words that are changed."""
# pylint: disable=invalid-name
l1 = s1.split(' ')
l2 = s2.split(' ')
dif = list(Differ().compare(l1, l2))
return " ".join(["\033[1m" + i[2:] + "\033[0m" if i[:1] == "+" else i[2:]
for i in dif if not i[:1] in "-?"])
def _set_diffs(self):
differ = difflib.Differ()
self.lines = []
lineno = 0
for line in differ.compare(self.old.splitlines(True),
self.new.splitlines(True)):
if line.startswith(' '):
lineno += 1
elif line.startswith('-'):
lineno += 1
self.lines.append(lineno)
def _set_diffs(self):
differ = difflib.Differ()
self.lines = []
lineno = 0
for line in differ.compare(self.old.splitlines(True),
self.new.splitlines(True)):
if line.startswith(' '):
lineno += 1
elif line.startswith('-'):
lineno += 1
self.lines.append(lineno)
def unique_contents(base_manifest_fn, image_manifest_fn):
"""
Get a list of files unique to the bundle image
Compare the bundle image manifest to the base image manifest and return
a list of files unique to the bundle image.
base_manifest_fn -- the base image manifest
image_manifest_fn -- the bundle image manifest
"""
import difflib
differ = difflib.Differ()
base_manifest_list = []
with open(base_manifest_fn) as base:
base_manifest_list = base.read().splitlines()
image_manifest_list = []
with open(image_manifest_fn) as image:
image_manifest_list = image.read().splitlines()
delta = list(differ.compare(base_manifest_list, image_manifest_list))
return delta_contents(delta)
# FIXME: Mariano proposed a similar method to OE-Core for package_manager
def output_difference(self, example, got, optionflags):
"""
Return a string describing the differences between the
expected output for a given example (`example`) and the actual
output (`got`). `optionflags` is the set of option flags used
to compare `want` and `got`.
"""
want = example.want
# If <BLANKLINE>s are being used, then replace blank lines
# with <BLANKLINE> in the actual output string.
if not (optionflags & DONT_ACCEPT_BLANKLINE):
got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
# Check if we should use diff.
if self._do_a_fancy_diff(want, got, optionflags):
# Split want & got into lines.
want_lines = want.splitlines(True) # True == keep line ends
got_lines = got.splitlines(True)
# Use difflib to find their differences.
if optionflags & REPORT_UDIFF:
diff = difflib.unified_diff(want_lines, got_lines, n=2)
diff = list(diff)[2:] # strip the diff header
kind = 'unified diff with -expected +actual'
elif optionflags & REPORT_CDIFF:
diff = difflib.context_diff(want_lines, got_lines, n=2)
diff = list(diff)[2:] # strip the diff header
kind = 'context diff with expected followed by actual'
elif optionflags & REPORT_NDIFF:
engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)
diff = list(engine.compare(want_lines, got_lines))
kind = 'ndiff with -expected +actual'
else:
assert 0, 'Bad diff option'
# Remove trailing whitespace on diff output.
diff = [line.rstrip() + '\n' for line in diff]
return 'Differences (%s):\n' % kind + _indent(''.join(diff))
# If we're not using diff, then simply list the expected
# output followed by the actual output.
if want and got:
return 'Expected:\n%sGot:\n%s' % (_indent(want), _indent(got))
elif want:
return 'Expected:\n%sGot nothing\n' % _indent(want)
elif got:
return 'Expected nothing\nGot:\n%s' % _indent(got)
else:
return 'Expected nothing\nGot nothing\n'