HTML编码/解码:Perl / Python输出不匹配

时间:2018-08-07 21:26:38

标签: python perl unicode utf-8

输入文本:ABC™Blue ® Testmix,200 x 20 µl rxns,2毫升(2 x 1毫升)

使用此在线工具验证输出以进行编码和解码: http://www.web2generators.com/html-based-tools/online-html-entities-encoder-and-decoder,网站返回的输出如下:

Decode Text 
ABC™ Blue<sup>®</sup> Testmix, 200 x 20 µl rxns, 2 ml (2 x 1 ml)

Encode Text
ABC&trade; Blue&lt;sup&gt;&reg;&lt;/sup&gt; Testmix, 200 x 20 &micro;l rxns, 2 ml (2 x 1 ml) 

我编写了Perl和Python代码来尝试查看是否可以获得相同的输出:

Python代码

from HTMLParser import HTMLParser
try:
    from html import escape  # python 3.x
except ImportError:
    from cgi import escape  # python 2.x


def htmldecode(s):
        h = HTMLParser()
        return h.unescape(s)

text = "ABC™ Blue<sup>®</sup> Testmix, 200 x 20 µl rxns, 2 ml (2 x 1 ml)"
print (htmldecode(text))
print (escape(htmldecode(text)))

Python输出的编码文本:

ABC™ Blue&lt;sup&gt;®&lt;/sup&gt; Testmix, 200 x 20 µl rxns, 2 ml (2 x 1 ml)

也尝试过Perl代码

use HTML::Entities;

my $input = "ABC™ Blue<sup>®</sup> Testmix, 200 x 20 µl rxns, 2 ml (2 x 1 ml)";
print encode_entities($input), "\n"

但是,输出是

ABC&acirc;&#132;&cent; Blue&lt;sup&gt;&Acirc;&reg;&lt;/sup&gt; Testmix, 200 x 20 &Acirc;&micro;l rxns, 2 ml (2 x 1 ml)

输出与http://www.web2generators.com/html-based-tools/online-html-entities-encoder-and-decoder返回的输出不匹配

1 个答案:

答案 0 :(得分:2)

您尚未告诉Perl您的脚本已保存在UTF-8中。只需添加

use utf8;

靠近脚本开头的位置(最佳位置在use strict;use warnings;之后)。

请参见utf8

相关问题