无法在 python 3 中写入包含 unicode 文本的 HtmlDiff 输出
Failing to write output of HtmlDiff containing unicode text in python 3
我正在尝试使用 python 的 difflib.HtmlDiff
模块比较两个阿拉伯语字符串。我研究了将 HtmlDiff
的输出写入文件的各种方法,但 none 似乎对我有用。目前尝试过的方法:
注意:在所有后续代码片段中,original
和mockinputs
是Unicode的HtmlDiff
所要求的字符串列表文本,特别是阿拉伯语。
Method 1
import difflib
hdiff = difflib.HtmlDiff()
html = hdiff.make_file(original, mockinputs)
with open('out_file.html', 'w', encoding='utf-8') as out_file:
out_file.write(html)
这运行没有错误,但是创建的 html 文件在浏览器中打开时是乱码(类似于 الرØÙ
)。
Method 2
(正如指出的 here)
import difflib
htmldiff = difflib.HtmlDiff()
html = htmldiff.make_file(original, mockinputs)
out_file = open('out_file.html', 'w')
out_file.write(html.encode('utf-8'))
out_file.close()
这给了我这个错误:
TypeError: must be str, not bytes
那么,如何将 HtmlDiff
生成的 Unicode 文本写入 python 3 中的 html 文件?
我正在使用 python 3.4.3.
According to the documentation,Python3.5 之前的 Python 版本中的 make_file
方法默认为 ISO-8859-1 字符集,不包括阿拉伯语。
此外,大多数浏览器都会看到 ISO-8859-1 并回退到 ASCII。因此,您必须在 Python3.5 中使用该方法才能获得 utf-8 或以不同的方式生成您想要的 HTML 输出。
编辑: 自 python 3.5.1 起,虽然 make_html
方法使用默认字符集 utf-8,但它的兄弟方法 make_table
不会,所以请小心使用后者!
我正在尝试使用 python 的 difflib.HtmlDiff
模块比较两个阿拉伯语字符串。我研究了将 HtmlDiff
的输出写入文件的各种方法,但 none 似乎对我有用。目前尝试过的方法:
注意:在所有后续代码片段中,original
和mockinputs
是Unicode的HtmlDiff
所要求的字符串列表文本,特别是阿拉伯语。
Method 1
import difflib
hdiff = difflib.HtmlDiff()
html = hdiff.make_file(original, mockinputs)
with open('out_file.html', 'w', encoding='utf-8') as out_file:
out_file.write(html)
这运行没有错误,但是创建的 html 文件在浏览器中打开时是乱码(类似于 الرØÙ
)。
Method 2
(正如指出的 here)
import difflib
htmldiff = difflib.HtmlDiff()
html = htmldiff.make_file(original, mockinputs)
out_file = open('out_file.html', 'w')
out_file.write(html.encode('utf-8'))
out_file.close()
这给了我这个错误:
TypeError: must be str, not bytes
那么,如何将 HtmlDiff
生成的 Unicode 文本写入 python 3 中的 html 文件?
我正在使用 python 3.4.3.
According to the documentation,Python3.5 之前的 Python 版本中的 make_file
方法默认为 ISO-8859-1 字符集,不包括阿拉伯语。
此外,大多数浏览器都会看到 ISO-8859-1 并回退到 ASCII。因此,您必须在 Python3.5 中使用该方法才能获得 utf-8 或以不同的方式生成您想要的 HTML 输出。
编辑: 自 python 3.5.1 起,虽然 make_html
方法使用默认字符集 utf-8,但它的兄弟方法 make_table
不会,所以请小心使用后者!