首页 > 解决方案 > HTML 编码/解码:Perl/Python 输出不匹配

问题描述

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

使用此在线工具验证编码和解码的输出: 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返回的输出不匹配

标签: pythonperlunicodeutf-8

解决方案


你还没有告诉 Perl 你的脚本是用 UTF-8 保存的。只需添加

use utf8;

靠近脚本开头的某个地方(最好的位置是在use strict;and之后use warnings;)。

utf8


推荐阅读