国际字符补全符

2024-04-25 11:49:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用以下代码来完成文本:

class MyCompleter(object):  # Custom completer

    def __init__(self, options):
        self.options = sorted(options) 

    def complete(self, text, state):
        if state == 0:  # on first trigger, build possible matches
            if text:  # cache matches (entries that start with entered text)
                self.matches = [s for s in self.options
                                    if s and s.startswith(text)]
            else:  # no text entered, all matches possible
                self.matches = self.options[:]
        # return match indexed by state
        try: 
            return self.matches[state]
        except IndexError:
            return None

def setCompleter(listOfItems):
  readline.parse_and_bind('tab: complete')
  readline.parse_and_bind('set editing-mode vi')
  completer = MyCompleter(listOfItems)
  readline.set_completer(completer.complete)

选项取自数据库。当我需要完成它的时候 不提供包含带diacritic的国际字符以外的选项。 我可以自定义代码来提供包含音调符号的选项吗?你知道吗


Tags: and代码textselfreadlinereturnifdef
1条回答
网友
1楼 · 发布于 2024-04-25 11:49:36

我怀疑您正在使用Python2;在Python3中,这可能“只起作用”。你知道吗

数据库正在返回unicode对象,readline库在使用前将其转换为字符串。默认情况下,此转换使用ascii编解码器,该编解码器对u"Name"运行良好,但对u"Näme"运行失败。你知道吗

替换这行可能有帮助:

completer = MyCompleter([item.encode('utf-8') for item in listOfItems])

相关问题 更多 >