Another one like 980, but using re's instead.
I haven't benchmarked these, but my guess is that 981 is faster for strings of pure digits and this is faster for larger chunks of text that happen to contain digits. If you're generating the numbers yourself, I'd just use 981 on a number right when you generate it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | import re
from django import template
from django.utils import translation
from django.template import defaultfilters
register = template.Library()
def _numdict(s):
return dict([(unicode(num), code) for num, code in enumerate(s)])
LANGUAGE_DIGITS = {
'ar': _numdict(u'\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669'),
'fa': _numdict(u'\u06f0\u06f1\u06f2\u06f3\u06f4\u06f5\u06f6\u06f7\u06f8\u06f9'),
}
digit = re.compile('\d')
def i18n_digits(uc_str, lang=None):
"""
Translate the digits a unicode string into the digits used in the given
language. If no language is given, the language code from the current
language is used.
"""
if lang is None:
lang = translation.get_language()
if lang not in LANGUAGE_DIGITS:
return uc_str
table = LANGUAGE_DIGITS[lang]
def replace_digit(m):
return table[m.group()]
return digit.sub(replace_digit, uc_str)
i18n_digits = defaultfilters.stringfilter(i18n_digits)
register.filter('i18n_digits', i18n_digits)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 8 months, 3 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 9 months ago
- Serializer factory with Django Rest Framework by julio 1 year, 3 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 4 months ago
- Help text hyperlinks by sa2812 1 year, 5 months ago
Comments
Nice to see your updates to snippet 980! I had just updated my version to regular expressions, when I saw your version. Maybe we could integrate our ideas into 'the one true i18n_digits snippet'?
#
Please login first before commenting.