Come faccio a decodificare entità HTML?
-
05-09-2019 - |
Domanda
Ecco una domanda veloce Perl:
Come posso convertire HTML caratteri speciali come ü
o '
normale testo ASCII?
Ho iniziato con qualcosa di simile:
s/\&#(\d+);/chr($1)/eg;
e potrebbe scrivere per tutti i caratteri HTML, ma qualche funzione in questo modo probabilmente già esiste?
Si noti che non ho bisogno di un full HTML-> Convertitore di testo. Ho già analizzare il HTML con il HTML::Parser
. Ho solo bisogno di convertire il testo con i caratteri speciali che sto ricevendo.
Soluzione
Date un'occhiata a HTML :: Enti :
use HTML::Entities;
my $html = "Snoopy & Charlie Brown";
print decode_entities($html), "\n";
Si può immaginare l'uscita.
Altri suggerimenti
Le risposte di cui sopra indicano come decodificare i soggetti in stringhe Perl, ma è anche chiesto come cambiare quelli in ASCII .
Supponendo che questo è davvero ciò che si vuole e non si desidera che tutti i caratteri unicode si può guardare al Testo :: modulo Unidecode da CPAN fare zapping tutti quei personaggi strani di nuovo in un insieme più o meno simile di caratteri ASCII:
use Text::Unidecode qw(unidecode);
use HTML::Entities qw(decode_entities);
my $source = '北亰';
print unidecode(decode_entities($source));
# That prints: Bei Jing
Note that there are hex-specified characters too. They look like this: é (é).
Use HTML::Entities' decode_entities to translate the entities into actual characters. To convert that to ASCII requires more work. I've used iconv (perl interface: Text::Iconv) with the transliterate option on with some success in the past. But if you are dealing with a limited set of entities, or you don't actually need it reduced to ASCII equivalents, you may be better off limiting what decode_entities produces or providing it with custom conversion maps. See the HTML::Entities doc.
There are a handful of predefined HTML entities - &
"
>
and so on - that you could hard code.
However, the larger case of numberic entities - {
- is going to be much harder, as those values are Unicode, and conversion to ASCII is going to range from difficult to impossible.