如何检测文本方向(如果是ltr或rlt)



在Python中,如何检测文本是否包含大多数ltr(从左到右(或rtl(从右到左(Unicode符号?

例如:

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

它也可以忽略像CJK这样允许两个方向的书写系统。

您可以通过这种方式与rtl语言的regexUnicode escapes一起使用(此处我使用了波斯语和阿拉伯语(:

代码:

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("سلام ایران"))

输出:

ltr
rtl

这是对这个问题的最新回应,我将把它包括在内以供将来参考。

确定字符串的方向很复杂。但是,如果您查看的是简单的近似值,则可以查看字符串中的双向属性值。下面,我将重点关注方向性强的角色,而忽略方向性弱的角色。

双向属性可通过unicodedata.bidirectional()获得

当方向未知时,控制文本方向的一种常见方法是使用第一个强启发式,选择与在文本中迭代时遇到的第一个强字符相匹配的方向。虽然这可能是错误的方向,但这是一种常见的倒退。

第二种方法是查看字符串中有多少字符是强LTR和强RTL,并选择字符串中字符最多的方向。

对于第一个强,类似于:

import unicodedata as ud
def first_strong(s):
properties = ['ltr' if v == "L" else 'rtl' if v in ["AL", "R"] else "-" for v in [ud.bidirectional(c) for c in list(s)]]
for value in properties:
if value == "ltr":
return "ltr"
elif value == "rtl":
return "rtl"
return None

对于主导方向:

from collections import Counter
import unicodedata as ud
def dominant_strong_direction(s):
count = Counter([ud.bidirectional(c) for c in list(s)])
rtl_count = count['R'] + count['AL'] + count['RLE'] + count["RLI"]
ltr_count = count['L'] + count['LRE'] + count["LRI"] 
return "rtl" if rtl_count > ltr_count else "ltr"

对于以下测试字符串,每个字符串都会产生以下结果:

s1 = "HTML : دليل تصميم وإنشاء المواقع على الإنترنت"
first_strong(s1)
# rtl
dominant_strong_direction(s1)
# rtl
s2 = "تبسيط إنشاء صفحات الويب باستخدام لغة HTML : أبسط طريقة لتعلم لغة HTML"
first_strong(s2)
# rtl
dominant_strong_direction(s2)
# rtl
s3 = "one שתיים three"
first_strong(s3)
# ltr
dominant_strong_direction(s3)
# ltr
s4 = ">one שתיים three<!"
first_strong(s4)
# rtl
dominant_strong_direction(s4)
# ltr

试图估计方向,可能会给出错误的结果。

最新更新