]> git.phdru.name Git - m_lib.git/blob - m_lib/rus/rus2lat.py
e7f731b1c24a7f79431ad7f9d2273db76eb6d5e6
[m_lib.git] / m_lib / rus / rus2lat.py
1 #! /usr/bin/env python
2 # -*- coding: koi8-r -*-
3
4 from __future__ import print_function
5
6 #
7 # Rus -> Lat transliteration (koi2lat and win2lat)
8 #
9
10 koi2lat_d = {
11    "А": "A",
12    "Б": "B",
13    "В": "V",
14    "Г": "G",
15    "Д": "D",
16    "Е": "E",
17    "Ж": "Zh",
18    "З": "Z",
19    "И": "I",
20    "Й": "Y",
21    "К": "K",
22    "Л": "L",
23    "М": "M",
24    "Н": "N",
25    "О": "O",
26    "П": "P",
27    "Р": "R",
28    "С": "S",
29    "Т": "T",
30    "У": "U",
31    "Ф": "F",
32    "Х": "H",
33    "Ц": "Ts",
34    "Ч": "Ch",
35    "Ш": "Sh",
36    "Щ": "Sh",
37    "Ъ": "'",
38    "Ь": "'",
39    "Ы": "Y",
40    "Э": "E",
41    "Ю": "Yu",
42    "Я": "Ya",
43    "а": "a",
44    "б": "b",
45    "в": "v",
46    "г": "g",
47    "д": "d",
48    "е": "e",
49    "ж": "zh",
50    "з": "z",
51    "и": "i",
52    "й": "y",
53    "к": "k",
54    "л": "l",
55    "м": "m",
56    "н": "n",
57    "о": "o",
58    "п": "p",
59    "р": "r",
60    "с": "s",
61    "т": "t",
62    "у": "u",
63    "ф": "f",
64    "х": "h",
65    "ц": "ts",
66    "ч": "ch",
67    "ш": "sh",
68    "щ": "sh",
69    "ъ": "'",
70    "ь": "'",
71    "ы": "y",
72    "э": "e",
73    "ю": "yu",
74    "я": "ya",
75 }
76
77 def make_xxx2lat(encoding="cp1251"):
78    d = {}
79    for k, v in koi2lat_d.items():
80       if isinstance(k, bytes):
81          k = k.decode("koi8-r")
82       k = k.encode(encoding)
83       d[k] = v
84    return d
85
86
87 from ..lazy.dict import LazyDictInitFunc
88 win2lat_d = LazyDictInitFunc(make_xxx2lat, encoding="cp1251")
89
90
91 def rus2lat(instr, rus2lat_d = koi2lat_d):
92    out = []
93    for c in instr:
94       c = rus2lat_d.get(c, c)
95       if isinstance(c, bytes):
96          c = c.decode('ascii')
97       elif isinstance(c, int):
98          c = chr(c)
99       out.append(c.encode('ascii'))
100    return b''.join(out)
101
102
103 koi2lat = rus2lat
104
105 def win2lat(instr):
106    return rus2lat(instr, win2lat_d)
107
108
109 if __name__ == "__main__":
110    Test = "Щербаков Игорь Григорьевич. АБВ xyz абв ЬЬЭЮЯ ъьэюя"
111    print("Test:", Test)
112    print("Тест:", koi2lat(Test))
113    if isinstance(Test, bytes):
114       Test = Test.decode("cp1251")
115    print("Тест:", win2lat(Test.encode("cp1251")))