【发布时间】: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 单词分隔符?这些编辑是如何做到的?
【问题讨论】:
-
您尝试过正则表达式吗? docs.python.org/3/library/re.html
-
见Unicode Word Boundary Rules。我不知道 Python 是否有实现该算法的核心模块,或者您是否必须安装一个(或者如果您是受虐狂,请自己编写一个)