]> git.phdru.name Git - m_lib.git/commitdiff
Fix encoding for Py3 compatibility
authorOleg Broytman <phd@phdru.name>
Mon, 25 Jul 2016 16:05:26 +0000 (19:05 +0300)
committerOleg Broytman <phd@phdru.name>
Mon, 25 Jul 2016 21:02:46 +0000 (00:02 +0300)
m_lib/rus/lat2rus.py
m_lib/rus/rus2lat.py

index 4e3d5805b4d4a6c98dd5683ebcf10cdaaeb8b70e..16d82f114d2982ba06f430bb8010a4f44fd08e34 100755 (executable)
@@ -81,27 +81,32 @@ lat2koi_d = {
    "%": ":",
    "^": ",",
    "&": ".",
-   "*": ";"
+   "*": ";",
 }
 
 
 def make_lat2xxx(encoding="cp1251"):
    d = {}
    for k, v in lat2koi_d.items():
-      v = unicode(v, "koi8-r").encode(encoding)
+      if isinstance(v, bytes):
+         v = v.decode("koi8-r")
+      v = v.encode(encoding)
       d[k] = v
    return d
 
 
-from m_lib.lazy.dict import LazyDictInitFunc
+from ..lazy.dict import LazyDictInitFunc
 lat2win_d = LazyDictInitFunc(make_lat2xxx, encoding="cp1251")
 
 
 def lat2rus(instr, lat2rus_d = lat2koi_d):
    out = []
    for c in instr:
-      out.append(lat2rus_d.get(c, c))
-   return ''.join(out)
+      c = lat2rus_d.get(c, c)
+      if isinstance(c, bytes):
+         c = c.decode('koi8-r')
+      out.append(c.encode('koi8-r'))
+   return b''.join(out)
 
 
 lat2koi = lat2rus
@@ -114,4 +119,7 @@ if __name__ == "__main__":
    Test = "Ghbdtn nt,t^ ghtrhfcysq vbh!"
    print("Test:", Test)
    print("Тест:", lat2koi(Test))
-   print("Тест:", unicode(lat2win(Test), "cp1251").encode("koi8-r"))
+   test = lat2win(Test)
+   if isinstance(test, bytes):
+      test = test.decode("cp1251")
+   print("Тест:", test.encode("koi8-r"))
index 7fbbf06b5948d6d4268a02a4fdc03d69cc8e5f59..e7f731b1c24a7f79431ad7f9d2273db76eb6d5e6 100755 (executable)
@@ -71,26 +71,33 @@ koi2lat_d = {
    "ы": "y",
    "э": "e",
    "ю": "yu",
-   "я": "ya"
+   "я": "ya",
 }
 
 def make_xxx2lat(encoding="cp1251"):
    d = {}
    for k, v in koi2lat_d.items():
-      k = unicode(k, "koi8-r").encode(encoding)
+      if isinstance(k, bytes):
+         k = k.decode("koi8-r")
+      k = k.encode(encoding)
       d[k] = v
    return d
 
 
-from m_lib.lazy.dict import LazyDictInitFunc
+from ..lazy.dict import LazyDictInitFunc
 win2lat_d = LazyDictInitFunc(make_xxx2lat, encoding="cp1251")
 
 
 def rus2lat(instr, rus2lat_d = koi2lat_d):
    out = []
    for c in instr:
-      out.append(rus2lat_d.get(c, c))
-   return ''.join(out)
+      c = rus2lat_d.get(c, c)
+      if isinstance(c, bytes):
+         c = c.decode('ascii')
+      elif isinstance(c, int):
+         c = chr(c)
+      out.append(c.encode('ascii'))
+   return b''.join(out)
 
 
 koi2lat = rus2lat
@@ -103,4 +110,6 @@ if __name__ == "__main__":
    Test = "Щербаков Игорь Григорьевич. АБВ xyz абв ЬЬЭЮЯ ъьэюя"
    print("Test:", Test)
    print("Тест:", koi2lat(Test))
-   print("Тест:", win2lat(unicode(Test, "koi8-r").encode("cp1251")))
+   if isinstance(Test, bytes):
+      Test = Test.decode("cp1251")
+   print("Тест:", win2lat(Test.encode("cp1251")))