簡體   English   中英

HTML編碼/解碼:Perl / Python輸出不匹配

[英]HTML Encode / Decode : Perl / Python output does not match

輸入文本:ABC™藍®Testmix,200×20微升rxns,2毫升(2×1ml)中

使用此在線工具驗證輸出以進行編碼和解碼: 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返回的輸出不匹配

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

use utf8;

靠近腳本開頭的位置(最佳位置在use strict; use warnings; )。

參見utf8

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM