Question on Python and Unicode

Status
Not open for further replies.

LogicProgrammer

Smack-Fu Master, in training
65
Subscriptor
Hi All,

I'm attempting to write a simple tool for transliterating Russian to English. I have the following structure:
Code:
character_map = {
    ...
}

def cyrillic_to_roman(x):
    """
    Given a cyrillic character, returns the corresponding roman character.
    """
    ch = x.encode('utf-8')
    if character_map.has_key(ch):
        return character_map[ch]
    else:
        return ch


def transliterate(text):
    """
    Transliterates the given string from cyrillic to roman characters.
    """
    romanized = [cyrillic_to_roman(ch) for ch in text]
    return "".join(romanized)

The implementation of the function cyrillic_to_roman seems ugly to me (especially the conversion of x to its unicode encoding ch). Is there a way to clean this up? The character_map is a dictionary mapping cyrillic characters to the roman variants.

Thank you kindly.
 

bdr

Wise, Aged Ars Veteran
137
LogicProgrammer":1sp67fng said:
To my knowledge I can't use the translate() method as cyrillic characters may be mapped onto one or more roman characters (for example: "щ" → "shch"), and last I checked you had to have strings of the same length for the translation table used.

Not true for unicode strings. This works for me:
Code:
#! /usr/bin/python
# -*- coding: utf-8 -*-

a= u'щ'
b = u'shch'

transtable = {
    ord(a): b
}

c = a + b
print c
print c.translate(transtable)

string.translate with unicode strings is quite undocumented. It's a dictionary with ordinal character numbers as keys. The replacement values are either ordinal chararcter numbers (aka a single character) or strings or None (for deletion). string.translate won't help you if you need to replace a sequence of characters.

Note that you will need to convert your input to unicode first, but I'd advice you to do anyway, since it makes it clear what kind of encoding you accept on input and what kind of encoding you will output.

Your 'x.encode('utf-8')' is necessary because you're working in an 8-bit codec but the keys in your character_map are written in utf-8. This is a mess.
 
Status
Not open for further replies.