本文整理汇总了Python中difflib.Differ.compare方法的典型用法代码示例。如果您正苦于以下问题:Python Differ.compare方法的具体用法?Python Differ.compare怎么用?Python Differ.compare使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类difflib.Differ
的用法示例。
在下文中一共展示了Differ.compare方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: getFirstLettersTheSame
# 需要导入模块: from difflib import Differ [as 别名]
# 或者: from difflib.Differ import compare [as 别名]
def getFirstLettersTheSame(wd1, wd2):
#возращает одинаковые первые буквы у двух идущих друг за другом слов
d = Differ()
diff = ''.join(d.compare(wd1, wd2))
diff = patternSpace.sub('',diff)
return patternLetters.match(diff)
示例2: get_changelist
# 需要导入模块: from difflib import Differ [as 别名]
# 或者: from difflib.Differ import compare [as 别名]
def get_changelist(old_text, new_text):
# copy and make sure we don't register changes simply
# because the endline characters changed (which happens
# when syncing windows and linux files, and when an otw
# unchanged line at the end of the file now has an endline
# character)
# splitlines() eliminate the last line if it's empty, and
# removes the endline characters, so they won't be considered
# for the diffs
old_text = old_text.splitlines()
old_text = [l for l in old_text]
new_text = new_text.splitlines()
new_text = [l for l in new_text]
lines_with_changes = None
differ = Differ()
differ_output = differ.compare(old_text, new_text)
lc = 0
lines_with_changes = []
for l in differ_output:
if l[0] == '+':
lines_with_changes.append(lc)
lc += 1
elif l[0] == '-':
pass
elif l[0] == ' ':
lc += 1
# there might also be the '?' case, but this doesn't affect the linecount
return "\n".join([str(l) for l in lines_with_changes])
示例3: str_diffs
# 需要导入模块: from difflib import Differ [as 别名]
# 或者: from difflib.Differ import compare [as 别名]
def str_diffs(self):
if self.actual == self.expected:
return ''
differ = Differ()
diffs = differ.compare(self.actual.splitlines(), self.expected.splitlines())
return 'Diffs:\n{0}'.format('\n'.join(diffs))
示例4: _
# 需要导入模块: from difflib import Differ [as 别名]
# 或者: from difflib.Differ import compare [as 别名]
def _(success, output):
d = Differ()
assert world.out.value() == output, '\n' + '\n'.join(d.compare(world.out.value().split('\n'), output.split('\n')))
if success == 'fail':
assert world.status.value() != 0
else:
assert world.status.value() == 0
示例5: testcode
# 需要导入模块: from difflib import Differ [as 别名]
# 或者: from difflib.Differ import compare [as 别名]
def testcode(self):
skipped_methods = []
fname = "examples/android/TestsAndroguard/bin/classes.dex"
parsed = parse_dex.read_dex(fname)
with open(fname, "rb") as f:
d = DalvikVMFormat(f.read())
dif = Differ()
for m in d.get_methods():
if not m.get_code():
continue
if m.get_method_idx() in skipped_methods:
continue
code = hexlify(m.get_code().get_raw())
self.assertEqual(parsed[m.get_method_idx()],
code,
"incorrect code for "
"[{}]: {} --> {}:\n"
"{}\ntries_size: {}, insns_size: {}\nSHOULD BE {}\n{}\n{}".format(m.get_method_idx(),
m.get_class_name(),
m.get_name(),
"".join(dif.compare(parsed[m.get_method_idx()],
code)),
m.get_code().tries_size,
m.get_code().insns_size,
hexlify(m.get_code().get_raw()),
parsed[m.get_method_idx()],
hexlify(m.get_code().code.get_raw())))
示例6: sortimports_linenum_msg
# 需要导入模块: from difflib import Differ [as 别名]
# 或者: from difflib.Differ import compare [as 别名]
def sortimports_linenum_msg(self, sort_result):
"""Parses isort.SortImports for line number changes and message
Uses a diff.Differ comparison of SortImport `in_lines`:`out_lines` to
yield the line numbers of import lines that have been moved or blank
lines added.
Args:
sort_imports (isort.SortImports): The isorts results object.
Yields:
tuple: A tuple of the specific isort line number and message.
"""
if sort_result.skipped:
raise StopIteration
self._fixup_sortimports_wrapped(sort_result)
self._fixup_sortimports_eof(sort_result)
differ = Differ()
diff = differ.compare(sort_result.in_lines, sort_result.out_lines)
line_num = 0
for line in diff:
if line.startswith(' ', 0, 2):
line_num += 1 # Ignore unchanged lines but increment line_num.
elif line.startswith('- ', 0, 2):
line_num += 1
if line.strip() == '-':
yield line_num, self.isort_blank_unexp
else:
yield line_num, self.isort_unsorted
elif line.strip() == '+':
# Include newline additions but do not increment line_num.
yield line_num + 1, self.isort_blank_req
示例7: all
# 需要导入模块: from difflib import Differ [as 别名]
# 或者: from difflib.Differ import compare [as 别名]
class TamperDetector:
"""
This will monitor periodically if the files which are being monitored are being
tampered with. It will remember the last line till where it has already
finished checking for tampering and check for tampering in the forecoming
lines.
If the line cannot be found at all (or portion of the line), it is
automatically declared as tampered.
"""
def __init__(self):
self._differ = Differ()
def tamper_detect(self, older_version_path, path):
current = open(path).readlines()
snapshot = open(older_version_path).readlines()
plus_minus = []
for line in self._differ.compare(current, snapshot):
plus_minus.append(line[0])
return self._is_tampered(plus_minus, len(snapshot))
def _is_tampered(self, plus_minus, no_of_lines_in_snapshot):
"""
"""
try:
if plus_minus.index('-') < no_of_lines_in_snapshot:
return True
except ValueError:
pass
return False
示例8: compare_config
# 需要导入模块: from difflib import Differ [as 别名]
# 或者: from difflib.Differ import compare [as 别名]
def compare_config(self, other=None, text=False):
"""
Compares running config with another config. This other config can be either the *running*
config or a :class:`~pyFG.forticonfig.FortiConfig`. The result of the comparison will be how to reach\
the state represented in the target config (either the *candidate* or *other*) from the *running*\
config.
Args:
* **other** (:class:`~pyFG.forticonfig.FortiConfig`) -- This parameter, if specified, will be used for the\
comparison. If it is not specified the candidate config will be used.
* **text** (bool):
* If ``True`` this method will return a text diff showing how to get from the running config to\
the target config.
* If ``False`` this method will return all the exact commands that needs to be run on the running\
config to reach the target config.
Returns:
See the explanation of the *text* arg in the section Args.
"""
if other is None:
other = self.candidate_config
if not text:
return self.running_config.compare_config(other)
else:
diff = Differ()
result = diff.compare(
self.running_config.to_text().splitlines(),
other.to_text().splitlines()
)
return '\n'.join(result)
示例9: diff
# 需要导入模块: from difflib import Differ [as 别名]
# 或者: from difflib.Differ import compare [as 别名]
def diff(request, page_info):
try:
id0 = request.GET['diff_1']
id1 = request.GET['diff_2']
submit0 = Web.get_result_details(submit=Submit(int(id0)))
submit1 = Web.get_result_details(submit=Submit(int(id1)))
submits = [submit0,submit1]
except:
return HttpResponseRedirect(reverse('results',args=[unicode(page_info.contest.id)]))
bar = StatusBar()
codes = []
ok = True
for i in [0,1]:
codes.append(submits[i].data)
if codes[i]==None or codes[i]=="":
ok = False
bar.errors.append('Could not render submit '+unicode(submits[i].submit.id)+'!')
diff_html = ""
if ok:
d = Differ()
for line in d.compare(codes[1].splitlines(True),codes[0].splitlines(True)):
if line[0]=='?':
continue
css = 'highlight_back'
if line[0]=='+':
css = 'highlight_pos'
if line[0]=='-':
css = 'highlight_neg'
diff_html += '<span class="'+css+'">'+escape(line)+'</span>'
return render_to_response('viewdiff.html',{'page_info' : page_info, 'submits' : submits, 'diff' : diff_html, 'status_bar' : bar})
示例10: mergeDiff
# 需要导入模块: from difflib import Differ [as 别名]
# 或者: from difflib.Differ import compare [as 别名]
def mergeDiff(global_, mooncake):
if global_.strip() == "":
return ["<!-- keep by customization: begin -->\n", mooncake+"\n", "<!-- keep by customization: end -->\n"]
leadingBlank = global_.find(global_.strip())
if global_.strip() == mooncake.strip():
return [global_ + "\n"]
globalText = handlePunctuation(global_.strip().split(" "))
mooncakeText = handlePunctuation(mooncake.strip().split(" "))
differ = Differ()
diff = list(differ.compare(globalText, mooncakeText))
i = 0
result = []
while i < len(diff):
if diff[i][0] == " ":
result.append(diff[i][2:])
i += 1
elif diff[i][0] == "-":
result.append("<!-- deleted by customization")
while i < len(diff) and diff[i][0] == "-":
result.append(diff[i][2:])
i += 1
result.append("-->")
elif diff[i][0] == "+":
result.append("<!-- keep by customization: begin -->")
while i < len(diff) and diff[i][0] == "+":
result.append(diff[i][2:])
i += 1
result.append("<!-- keep by customization: end -->")
else:
i += 1
text, count, percentage = mergeDeleteAndKeep2(result)
if ((count < 0.1*float(len(globalText)) or count == 1) and percentage < 0.5) or global_.strip().find(mooncake.strip()) != -1 or mooncake.strip().find(global_.strip()) != -1:
return [global_[:leadingBlank]+text.replace(" \b","").replace("\b","").replace("--> <!--", "--><!--")]
return ["<!-- deleted by customization\n", global_+"\n", "-->\n", "<!-- keep by customization: begin -->\n", mooncake+"\n", "<!-- keep by customization: end -->\n"]
示例11: diff
# 需要导入模块: from difflib import Differ [as 别名]
# 或者: from difflib.Differ import compare [as 别名]
def diff(self, oldobj, obj):
"""Create a diff of `obj` vs. `oldobj`; description is handled using difflib module."""
difflist = []
skip = "description_html".split()
nl = '\n'
for fld in obj._meta.fields:
name = fld.name
if name not in skip:
oldval = getattr(oldobj, fld.name)
val = getattr(obj, fld.name)
if name == "description":
olddesc = oldobj.description.splitlines(1)
desc = obj.description.splitlines(1)
if olddesc:
olddesc[-1] = olddesc[-1].strip() + '\r\n'
if desc:
desc[-1] = desc[-1].strip() + '\r\n'
d = Differ()
result = list(d.compare(olddesc, desc))
# note: Differ returns full(?) content when there are no changes!!!?
if olddesc != desc:
difflist.extend( [nl + "Description diff:" + nl] + result + [nl] )
else:
if oldval != val:
difflist.append("%s: changed from '%s' to '%s'" % (fld.name, oldval, val) + nl)
diff = ''.join(difflist)
return diff
示例12: diff
# 需要导入模块: from difflib import Differ [as 别名]
# 或者: from difflib.Differ import compare [as 别名]
def diff(dir1, dir2, fn1, fn2):
filenames_list1 = sorted(map(fn1, os.listdir(dir1)))
filenames_list2 = sorted(map(fn2, os.listdir(dir2)))
df = Differ()
result = df.compare(filenames_list1, filenames_list2)
with open(OUTPUT_FILE, 'w') as f:
f.write('\n'.join(result))
示例13: diff_lines
# 需要导入模块: from difflib import Differ [as 别名]
# 或者: from difflib.Differ import compare [as 别名]
def diff_lines(old, new):
d = Differ()
diff = list(d.compare(old, new))
for line in diff[:]:
if line.startswith(" "):
diff.remove(line)
return diff
示例14: diff_inside
# 需要导入模块: from difflib import Differ [as 别名]
# 或者: from difflib.Differ import compare [as 别名]
def diff_inside(_dir, type1, type2):
files = os.listdir(_dir)
filenames_list1 = sorted(map(lambda x:x.replace(type1, ''), filter(lambda f: f.endswith(type1), files)))
filenames_list2 = sorted(map(lambda x:x.replace(type2, ''), filter(lambda f: f.endswith(type2), files)))
df = Differ()
result = df.compare(filenames_list1, filenames_list2)
with open(OUTPUT_FILE, 'w') as f:
f.write('\n'.join(result))
示例15: assertFileMatches
# 需要导入模块: from difflib import Differ [as 别名]
# 或者: from difflib.Differ import compare [as 别名]
def assertFileMatches(self, expected, actual):
areSame = filecmp.cmp(expected, actual)
if not areSame:
d = Differ()
expectedLines = open(expected).readlines()
actualLines = open(actual).readlines()
result = list(d.compare(expectedLines, actualLines))
sys.stdout.writelines(result)
self.assertTrue(areSame)