File size: 2,669 Bytes
46c2986
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# -*- coding: utf-8 -*-
import sys

sys.stdout.reconfigure(encoding='utf-8')

VOWELS = {
    'अ': 'a', 'आ': 'aa', 'इ': 'i', 'ई': 'ee', 'उ': 'u', 'ऊ': 'oo', 'ऋ': 'ri',
    'ए': 'e', 'ऐ': 'ai', 'ओ': 'o', 'औ': 'au', 'अं': 'an', 'अः': 'ah'
}
MATRAS = {
    'ा': 'aa', 'ि': 'i', 'ी': 'ee', 'ु': 'u', 'ू': 'oo', 'ृ': 'ri',
    'े': 'e', 'ै': 'ai', 'ो': 'o', 'ौ': 'au', 'ं': 'n', 'ँ': 'n', 'ः': 'h', '्': ''
}
CONSONANTS = {
    'क': 'k', 'ख': 'kh', 'ग': 'g', 'घ': 'gh', 'ङ': 'ng',
    'च': 'ch', 'छ': 'chh', 'ज': 'j', 'झ': 'jh', 'ञ': 'ny',
    'ट': 't', 'ठ': 'th', 'ड': 'd', 'ढ': 'dh', 'ण': 'n',
    'त': 't', 'थ': 'th', 'द': 'd', 'ध': 'dh', 'न': 'n',
    'प': 'p', 'फ': 'ph', 'ब': 'b', 'भ': 'bh', 'म': 'm',
    'य': 'y', 'र': 'r', 'ल': 'l', 'व': 'v',
    'श': 'sh', 'ष': 'sh', 'स': 's', 'ह': 'h',
    'क़': 'q', 'ख़': 'kh', 'ग़': 'gh', 'ज़': 'z', 'ड़': 'r', 'ढ़': 'rh', 'फ़': 'f'
}

def devanagari_to_hinglish(text):
    out = []
    i = 0
    n = len(text)
    while i < n:
        if i + 1 < n and text[i:i+2] in CONSONANTS:
            base = CONSONANTS[text[i:i+2]]
            i += 2
            if i < n and text[i] in MATRAS:
                out.append(base + MATRAS[text[i]])
                i += 1
            else:
                out.append(base + ('a' if i < n and text[i] not in ' \t\n.,!?;:()[]' else ''))
        elif text[i] in CONSONANTS:
            base = CONSONANTS[text[i]]
            i += 1
            if i < n and text[i] in MATRAS:
                out.append(base + MATRAS[text[i]])
                i += 1
            else:
                if i == n or text[i] in ' \t\n.,!?;:()[]\'"':
                    out.append(base)
                else:
                    out.append(base + 'a')
        elif text[i] in VOWELS:
            out.append(VOWELS[text[i]])
            i += 1
        elif text[i] in MATRAS:
            out.append(MATRAS[text[i]])
            i += 1
        else:
            out.append(text[i])
            i += 1
    return ''.join(out)

if __name__ == '__main__':
    s1 = "भारत एक महान और प्राचीन देश है। हम सब मिलकर इसे आगे बढ़ाएंगे।"
    s2 = "आप आज क्या कर रहे हो? मुझे कुछ नया सिखाओ।"
    s3 = "8D problem solving me D4 root cause analysis sabse important stage hoti hai."
    print("S1:", devanagari_to_hinglish(s1))
    print("S2:", devanagari_to_hinglish(s2))
    print("S3:", devanagari_to_hinglish(s3))