Skip to content

Instantly share code, notes, and snippets.

@bmentges
Created August 20, 2009 21:03
Show Gist options
  • Save bmentges/171372 to your computer and use it in GitHub Desktop.
Save bmentges/171372 to your computer and use it in GitHub Desktop.
Transliteração: javascript, python, ruby
/* requires jQuery 1.3.2 minimum */
$.trocaAcentosECaracteresEspeciais = function (texto) {
var afrom = "á,à,ã,â,ä,Á,À,Ã,Â,Ä";
var efrom = "é,è,ê,ë,É,È,Ê,Ë";
var ifrom = "í,ì,î,ï,Í,Ì,Î,Ï";
var ofrom = "ó,ò,õ,ô,ö,Ó,Ò,Õ,Ô,Ö";
var ufrom = "ú,ù,û,ü,Ú,Ù,Û,Ü";
var outrosfrom = "ñ,Ñ,ç,Ç,&,@";
var from = afrom + "," + efrom + "," + ifrom + "," + ofrom + "," + ufrom + "," + outrosfrom;
var ato = "a,a,a,a,a,A,A,A,A,A";
var eto = "e,e,e,e,E,E,E,E";
var ito = "i,i,i,i,I,I,I,I";
var oto = "o,o,o,o,o,O,O,O,O,O";
var uto = "u,u,u,u,U,U,U,U";
var outrosto = "n,N,c,C,e,a";
var to = ato + "," + eto + "," + ito + "," + oto + "," + uto + "," + outrosto;
var re = new RegExp("[^A-Za-z0-9.,:;!?\"'&@+*/#%=()_\-]+", "g");
return $.trim($.__transliterate__(texto, from, to).replace(re, " ").toLowerCase());
};
$.__transliterate__ = function (texto, from, to) {
var fromChars = from.split(",");
var toChars = to.split(",");
var mapTable = {};
for(i = 0; i < fromChars.length; i++) {
var c = i < toChars.length ? toChars[i] : "";
mapTable[fromChars[i]] = c;
}
var re = new RegExp(fromChars.join("|"), "g");
texto = texto.replace(re, function(c) {
return mapTable[c];
});
return texto;
};
/* requires qUnit - unit tests */
test("Verifica a funcao de normalizacao", function() {
expect(7);
ok($.normalizaBusca("água") == "agua", "[agua] A palavra foi normalizada com sucesso");
ok($.normalizaBusca("áàãâä") == "aaaaa", "[aaaaa] A palavra foi normalizada com sucesso");
ok($.normalizaBusca("áàãâägua") == "aaaaagua", "[aaaagua] A palavra foi normalizada com sucesso");
ok($.normalizaBusca("água àgua ãgua âgua ägua") == "agua agua agua agua agua", "[agua agua agua agua agua] A palavra foi normalizada com sucesso");
ok($.normalizaBusca("élefântè èlefante êlefante ëlefante") == "elefante elefante elefante elefante", "[elefante elefante elefante elefante] A palavra foi normalizada com sucesso");
ok($.normalizaBusca(" um| dois||tres|^ qù@trõ~}CíNcô & seïs [") == "um dois tres quatro cinco e seis", "[um dois tres quatro cinco e seis] A palavra foi normalizada com sucesso");
ok($.normalizaBusca(" ") == "", "[] Se buscar so' por espacos, deve normalizar para vazio");
});
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from unicodedata import normalize
def remover_acentos(txt, codif='utf-8'):
''' Devolve cópia de uma str substituindo os caracteres
acentuados pelos seus equivalentes não acentuados.
ATENÇÃO: carateres gráficos não ASCII e não alfa-numéricos,
tais como bullets, travessões, aspas assimétricas, etc.
são simplesmente removidos!
>>> remover_acentos('[ACENTUAÇÃO] ç: áàãâä! éèêë? íì&#297;îï, óòõôö; úù&#361;ûü.')
'[ACENTUACAO] c: aaaaa! eeee? iiiii, ooooo; uuuuu.'
'''
return normalize('NFKD', txt.decode(codif)).encode('ASCII','ignore')
def to_permalink(texto)
texto = remover_acentos(texto)
translation_to = 'ascii//translit//IGNORE'
translation_from = 'utf-8'
result = Iconv.iconv(translation_to, translation_from, texto).to_s
result.gsub!(/[^\x00-\x7F]+/, '')
result.gsub!(/[^\w_ \-]+/i, '')
result.gsub!(/[ \-]+/i, '-')
result.gsub!(/^\-|\-$/i, '')
result.downcase
end
def remover_acentos(texto)
return texto if texto.blank?
texto = texto.gsub(/[á|à|ã|â|ä]/, 'a').gsub(/(é|è|ê|ë)/, 'e').gsub(/(í|ì|î|ï)/, 'i').gsub(/(ó|ò|õ|ô|ö)/, 'o').gsub(/(ú|ù|û|ü)/, 'u')
texto = texto.gsub(/(Á|À|Ã|Â|Ä)/, 'A').gsub(/(É|È|Ê|Ë)/, 'E').gsub(/(Í|Ì|Î|Ï)/, 'I').gsub(/(Ó|Ò|Õ|Ô|Ö)/, 'O').gsub(/(Ú|Ù|Û|Ü)/, 'U')
texto = texto.gsub(/ñ/, 'n').gsub(/Ñ/, 'N')
texto = texto.gsub(/ç/, 'c').gsub(/Ç/, 'C')
texto
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment