Eupator
Eupator

Reputation: 29

How to write a program in Python 3 to convert a name written in Latin to a name written in Russian Cyrillic?

I need to write a program in Python 3 that will take the user's name in Latin alphabet as an input and then transliterate the Latin characters into Russian Cyrillic characters and then print it. I have equalized each Latin letter to their Russian counterpart and then I thought about using if statements to execute the conversion for each character but of course it didn't work out, because when the user types in more than one character, the program returns the else statement. I need the program to accept input strings and print the counterpart letters accordingly one after another. If the user types in "David", the program should print Давид.

Here is my funny code:

A = "А"
B = "Б"
V = "В"
G = "Г"
D = "Д"
E = "Э"
YE = "Е"
YO = "Ё"
ZH = "Ж"
Z = "З"
I = "И"
Y = "Й"
K = "К"
L = "Л"
M = "М"
N = "Н"
O = "О"
P = "П"
R = "Р"
S = "С"
T = "Т"
U = "У"
F = "Ф"
H = "Х"
C = "Ц"
CH = "Ч"
SH = "Ш"
SHCH = "Щ"
YU = "Ю"
YA = "Я"
YY = "Ы"
a = "а"
b = "б"
v = "в"
g = "г"
d = "д"
e = "э"
ye = "е"
yo = "ё"
zh = "ж"
z = "з"
i = "и"
y = "й"
k = "к"
l = "л"
m = "м"
n = "н"
o = "о"
p = "п"
r = "р"
s = "с"
t = "т"
u = "у"
f = "ф"
h = "х"
c = "ц"
ch = "ч"
sh = "ш"
shch = "щ"
yy = "ы"
yu = "ю"
ya = "я"

print("Latin-to-Russian transliterator")
trans = input("Please enter your name: ")

if trans == "a":
   print(a)

elif trans == "b":
   print(b)
elif trans == "c":
   print(c)
else:
   print("sorry")

Upvotes: 1

Views: 351

Answers (1)

Joran Beasley
Joran Beasley

Reputation: 114038

use a lookup dictionary with regex

lookup = dict(A = "А",
B = "Б",
V = "В",
G = "Г",
D = "Д",
E = "Э",
YE = "Е",
YO = "Ё",
ZH = "Ж",
Z = "З",
I = "И",
Y = "Й",
K = "К",
L = "Л",
M = "М",
N = "Н",
O = "О",
P = "П",
R = "Р",
S = "С",
T = "Т",
U = "У",
F = "Ф",
H = "Х",
C = "Ц",
CH = "Ч",
SH = "Ш",
SHCH = "Щ",
YU = "Ю",
YA = "Я",
YY = "Ы",
a = "а",
b = "б",
v = "в",
g = "г",
d = "д",
e = "э",
ye = "е",
yo = "ё",
zh = "ж",
z = "з",
i = "и",
y = "й",
k = "к",
l = "л",
m = "м",
n = "н",
o = "о",
p = "п",
r = "р",
s = "с",
t = "т",
u = "у",
f = "ф",
h = "х",
c = "ц",
ch = "ч",
sh = "ш",
shch = "щ",
yy = "ы",
yu = "ю",
ya = "я")

now sort the keys from longest to shortest length

sorted_keys = sorted(lookup.keys(),reversed=True)

do an re.sub on any matches

result = re.sub("(%s)"%("|".join(sorted_keys)),
                # replacer function
                lambda m:lookup.get(m.group(1),m.group(1)),
                #input
                input("Enter Word: "))    
print(result)

by sorting from longest to shortest you will prefer longer matches, thus ensuring multibyte characters are properly interpretted

Upvotes: 4

Related Questions