import difflib
import webbrowser
# - classes -
class MyHTML(difflib.HtmlDiff):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# append new styles inside new class
self._styles = self._styles + """
table.diff {width: 300px}
.diff_sub {display: inline-block; word-break: break-word;}
.diff_add {display: inline-block; word-break: break-word;}
"""
# function from source code - I remove only `nowrap="nowrap"`
def _format_line(self,side,flag,linenum,text):
"""Returns HTML markup of "from" / "to" text lines
side 0 or 1 indicating "from" or "to" text
flag indicates if difference on line
linenum line number (used for line number column)
text line text to be marked up
"""
try:
linenum = '%d' % linenum
id = ' id="%s%s"' % (self._prefix[side],linenum)
except TypeError:
# handle blank lines where linenum is '>' or ''
id = ''
# replace those things that would get confused with HTML symbols
text=text.replace("&","&").replace(">",">").replace("<","<")
# make space non-breakable so they don't get compressed or line wrapped
text = text.replace(' ',' ').rstrip()
return '<td class="diff_header"%s>%s</td><td>%s</td>' \
% (id,linenum,text)
# - main -
d = MyHTML()
# >>> changing styles after creating `MyHTML` or in original `HtmlDiff <<<
#d._styles = d._styles + """
#table.diff {width: 300px}
#.diff_sub {display: inline-block; word-break: break-word;}
#.diff_add {display: inline-block; word-break: break-word;}
#"""
#d._file_template = """new template"""
lines1 = ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa']
lines2 = ['XXXXXXXXXXXXXaaaaaaaaaYYYaaaaaaZZZZZZZZZZZaaaaZZZZZZZZ']
html = d.make_file(lines1, lines2)
with open('output.html', 'w') as fh:
fh.write(html)
webbrowser.open('output.html')
较短版本
import difflib
import webbrowser
d = HtmlDiff(wrapcolumn=10)
d._file_template = """new template with %(charset)s %(styles)s %(table)s %(legend)s"""
#d._styles = """new styles"""
lines1 = ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa']
lines2 = ['XXXXXXXXXXXXXaaaaaaaaaYYYaaaaaaZZZZZZZZZZZaaaaZZZZZZZZ']
html = d.make_file(lines1, lines2)
with open('output.html', 'w') as fh:
fh.write(html)
webbrowser.open('output.html')
您可以在
HtmlDiff
中使用wrapcolumn=
没有
wrapcolumn=
与
wrapcolumn=10
编辑:
我没有测试它,但在diff的源代码中,您可以看到隐藏变量_styles、_table_template、_file_template,您可以在HtmlDiff中替换这些变量以生成不同的HTML。通过这种方式,您可以添加类和样式来格式化它
它可能还需要更改隐藏的_format_line以删除
nowrap="nowrap"
编辑:
我使用
HtmlDiff
创建自己的类,使用新的_format_line()
而不使用nowrap="nowrap"
,现在我可以添加带有width
和word-break
的样式较短版本
相关问题 更多 >
编程相关推荐