Login

Localized digits

Author:
jcassee
Posted:
August 14, 2008
Language:
Python
Version:
.96
Tags:
i18n
Score:
0 (after 0 ratings)

Arabic and Farsi languages use their own digits. This template filter translates any digits in the supplied unicode string into the correct ones for the language. The previous version used StringIO to parse the string one character at a time. It now uses regular expressions.

I just saw that kcarnold created two snippets that also removed the need for StringIO: 981 and 982. That last snippet is almost the same as this one.

 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
import re
from django import template
from django.utils import translation
from django.template import defaultfilters

register = template.Library()

LANGUAGE_DIGITS = {
    'ar': u'\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669',
    'fa': u'\u06f0\u06f1\u06f2\u06f3\u06f4\u06f5\u06f6\u06f7\u06f8\u06f9',
}
digit_re = re.compile('\d')

def i18n_digits(str, lang=None):
    """
    Translate the digits in a string into the digits used in the given
    language. If no language is given, the language code from the current
    language is used. While the input can be a basic string, the output will
    always be unicode.
    """
    uc_str = unicode(str)
    if lang is None:
        lang = translation.get_language()
    digits_table = LANGUAGE_DIGITS.get(lang, None)
    if digits_table is not None:
        def digit_replace(match):
            return digits_table[int(match.group())]
        return digit_re.sub(digit_replace, uc_str)
    else:
        return uc_str
i18n_digits = defaultfilters.stringfilter(i18n_digits)
register.filter('i18n_digits', i18n_digits)

More like this

  1. Localized digits by kcarnold 6 years, 11 months ago
  2. Localized digits (re) by kcarnold 6 years, 11 months ago
  3. Currency Object by Rupe 6 years, 2 months ago
  4. Currency Form Field by Rupe 6 years, 2 months ago
  5. A few jinja2 filters like django ones by brondsem 6 years, 4 months ago

Comments

Please login first before commenting.