How to detect text orientation (if it’s ltr or rlt)

Viewed 36

In Python, how to detect if a peace of text has a majority of ltr (left-to-right) or rtl (right-to-left) Unicode symbols?

As example someting like that:

>>> guesstextorientation("abطcdαδ")
"ltr"
>>> guesstextorientation("עִבְרִיתa")
"rtl"

It could also ignore the writing systems where the two directions are allowed like CJK.

1 Answers

You can use this way with regex and Unicode escapes of rtl languages( here I used Persian and Arabic):

Code:

import re

# Persian \u0600-\u06FF
# Arabic \u0627-\u064a

def guesstextorientation(text):
    
    lang = ['ltr','rtl']
    # you need to add other languages pattern here
    pattern = re.compile('[\u0627-\u064a]|[\u0600-\u06FF]')
    
    return lang[len(re.findall(pattern, text)) > (len(text)/2)]

print(guesstextorientation("abطcdαδ"))
print(guesstextorientation("سلام ایران"))

Output:

ltr
rtl
Related