【问题标题】:Inserting LTR marks automatically自动插入 LTR 标记
【发布时间】:2023-03-23 12:24:02
【问题描述】:

我正在为一个项目使用双向文本(混合英语和希伯来语)。文本以 HTML 格式显示,因此有时需要 LTR 或 RTL 标记(‎‏)才能正确显示标点符号等“弱字符”。由于技术限制,源文本中不存在这些标记,因此我们需要添加它们以使最终显示的文本正确显示。

例如,以下文本:(example: מדגם) sample 在从右到左的模式下呈现为 sample (מדגם :example)。更正后的字符串看起来像 ‎(example:‎ מדגם) sample 并呈现为 sample (מדגם (example:

我们希望即时插入这些标记,而不是重新创作所有文本。起初这似乎很简单:只需将‎ 附加到每个标点符号实例。但是,一些需要即时修改的文本包含 HTML 和 CSS。造成这种情况的原因是不幸且不可避免的。

没有解析 HTML/CSS,有没有已知的动态插入 Unicode 方向标记(伪强字符)的算法?

【问题讨论】:

  • Date().getYear() 已被弃用,使用 Date().getFullYear() ref

标签: html unicode internationalization


【解决方案1】:

我不知道有一种算法可以在不解析的情况下安全地将方向标记插入 HTML 字符串。将 HTML 解析为 DOM 并操作文本节点是确保您不会意外在 <script><style> 标记内的文本中添加方向标记的最安全方法。

这是一个简短的 Python 脚本,可以帮助您自动转换文件。如有必要,逻辑应该易于翻译成其他语言。我对您尝试编码的 RTL 规则不够熟悉,但您可以调整正则表达式 '(\W([^\W]+)(\W)' 和替换模式 ur"\u200e\1\2\3\u200e" 以获得预期结果:

import re
import lxml.html

_RE_REPLACE = re.compile('(\W)([^\W]+)(\W)', re.M)

def _replace(text):
    if not text:
        return text
    return _RE_REPLACE.sub(ur'\u200e\1\2\3\u200e', text)

text = u'''
<html><body>
    <div>sample (\u05de\u05d3\u05d2\u05dd :example)</div>
    <script type="text/javascript">var foo = "ignore this";</script>
    <style type="text/css">div { font-size: 18px; }</style>
</body></html>
'''

# convert the text into an html dom
tree = lxml.html.fromstring(text)
body = tree.find('body')
# iterate over all children of <body> tag
for node in body.iterdescendants():
    # transform text with trails after the current html tag
    node.tail = _replace(node.tail)
    # ignore text inside script and style tags
    if node.tag in ('script','style'):
        continue
    # transform text inside the current html tag
    node.text = _replace(node.text)

# render the modified tree back to html
print lxml.html.tostring(tree)

输出:

python convert.py

<html><body>
    <div>sample (&#1502;&#1491;&#1490;&#1501; &#8206;:example)&#8206;</div>
    <script type="text/javascript">var foo = "ignore this";</script>
    <style type="text/css">div { font-size: 18px; }</style>
</body></html>

【讨论】:

  • 让这变得更加困难的一件事是破坏了 HTML,但是一个宽容的解析器可以帮助解决这个问题。对于这个应用程序,我们实际上是在处理 HTML 片段,所以解析是粗略的。真正的解决方案是在流程中更早地进行更改。
猜你喜欢
  • 1970-01-01
  • 2011-02-14
  • 2010-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多