【问题标题】:How to decide which unicode character is a word seperator?如何确定哪个 unicode 字符是单词分隔符?
【发布时间】:2020-12-29 21:41:15
【问题描述】:

在大多数文本编辑器中,例如 notepad-plus-plus 和 vscode,当您双击一个字符时,它们会选择整个单词。我很好奇如何实现它,这个函数(在 Python 中)可能是:

separators = 'some characters' # word separators
def select_word_at_offset(line, offset):
    line_length = len(line)
    if offset < 0 or offset > line_length:
        raise RuntimeError('offset is not a valid index of line')
    
    # ignore the cases when you double click on a word separator

    start_index = offset
    end_index = offset

    # look left to find the start index
    while start_index >= 0:
        if line[start_index] in separators:
            break
        start_index -= 1

    # look right to find the end index
    while end_index < line_length:
        if line[start_index] in separators:
            break
        end_index += 1
    return start_index + 1, end_index - 1

如果只考虑 ASCII 字符,这很容易做到,但要支持 unicode,我必须决定应该将哪个 unicode 字符视为单词分隔符。不管是白名单还是黑名单,都是一个很长的名单。

那么,有没有什么简单的方法可以覆盖所有的 unicode 单词分隔符?这些编辑是如何做到的?

【问题讨论】:

标签: string unicode


【解决方案1】:

感谢@Shawn,Unicode Word Boundary Rules 帮助很大,我阅读了this post,看起来 perl 已经掌握了,我从未学过 perl,所以还需要一些时间来确认。

我发现vscode 使用这些字符作为单词分隔符:

export const USUAL_WORD_SEPARATORS = '`~!@#$%^&*()-=+[{]}\\|;:\'",.<>/?';

显然,他们没有考虑非英语语言符号,例如,它表示中文句子的结尾。

【讨论】:

    猜你喜欢
    • 2012-06-18
    • 2013-06-28
    • 2011-09-11
    • 1970-01-01
    • 2016-06-23
    • 2017-10-25
    • 2012-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多