gpt4 book ai didi

python - 如何在 Python 中着色用户输入?

转载 作者:行者123 更新时间:2023-12-04 07:25:13 24 4
gpt4 key购买 nike

我正在创建一个命令行计算器工具,我想让它在用户输入时格式化用户输入,类似于 Fish 和 Powershell 所做的( screenshots )。
目前,我能想到的唯一简单的方法是一次获取一个字符,然后将格式化的行重新打印到屏幕上。

# This code is probably very dodgy, 
# it's just to give you an idea what I'm thinking
# Use external getch module to get input without echoing to screen
from getch import getch
inp = ""
while True:
char = getch()
if char == '\n': break
if char == '\b': inp = inp[:-1]
else: inp += char
# Print with carriage return so that next input overwrites it
print(colourFormatInput(inp) + '\r')
# Outside loop: process input and devliver results
虽然这在技术上可行,但我觉得这是大量的手动工作,如果我想添加诸如使用箭头键移动光标位置之类的功能,只会变得更加复杂。
有没有一种简单的方法来获得这种功能而不必自己编写所有代码?

最佳答案

你可以用 prompt_toolkit 来做到这一点
如果您需要,这里是文档:

  • Getting Started
  • Asking for input/prompts

  • 您可以通过以下示例将语法突出显示添加到输入中:

    Adding syntax highlighting is as simple as adding a lexer. All of the Pygments lexers can be used after wrapping them in a PygmentsLexer. It is also possible to create a custom lexer by implementing the Lexer abstract base class.

    from pygments.lexers.html import HtmlLexer
    from prompt_toolkit.shortcuts import prompt
    from prompt_toolkit.lexers import PygmentsLexer

    text = prompt('Enter HTML: ', lexer=PygmentsLexer(HtmlLexer))
    print('You said: %s' % text)

    Output of the above


    以与上述相同的方式,您可以创建自定义 prompt_toolkit.lexers.Lexer计算器高亮就像下面的例子。在这里,我创建了一个自定义帮助器类:
    from typing import Callable
    from prompt_toolkit.document import Document
    from prompt_toolkit.formatted_text.base import StyleAndTextTuples
    from prompt_toolkit.formatted_text import FormattedText
    from prompt_toolkit.shortcuts import prompt
    import prompt_toolkit.lexers
    import re

    class CustomRegexLexer(prompt_toolkit.lexers.Lexer):
    def __init__(self, regex_mapping):
    super().__init__()
    self.regex_mapping = regex_mapping

    def lex_document(self, document: Document) -> Callable[[int], StyleAndTextTuples]:
    def lex(_: int):
    line = document.text
    tokens = []
    while len(line) != 0:
    for pattern, style_string in self.regex_mapping.items():
    match: re.Match = pattern.search(line)

    if not match:
    continue
    else:
    # print(f"found_match: {match}")
    pass
    match_string = line[:match.span()[1]]
    line = line[match.span()[1]:]
    tokens.append((style_string, match_string))
    break
    return tokens
    return lex
    现在实现了上面的辅助类,我们可以创建我们的正则表达式模式和它们各自的样式,要了解更多关于样式字符串的内容,请访问 this page
    # Making regex for different operators. Make sure you add `^` anchor
    # to the start of all the patterns
    operators_allowed = ["+", "-", "/", "*", "(", ")", "=", "^"]
    operators = re.compile("^["+''.join([f"\\{x}" for x in operators_allowed])+"]")
    numbers = re.compile(r"^\d+(\.\d+)?")
    text = re.compile(r"^.")


    regex_mapping = {
    operators: "#ff70e5", # Change colors according to your requirement
    numbers: "#ffa500",
    text: "#2ef5ff",
    }

    MyCalculatorLexer = CustomRegexLexer(regex_mapping)
    创建词法分析器后,您现在可以在函数提示中使用词法分析器:
    text = prompt("Enter Equation: ", lexer=MyCalculatorLexer)

    # Or

    def input_maths(message):
    return prompt(message, lexer=MyCalculatorLexer)

    text = input_maths("Enter Equation: ")
    这是一些示例输出:
    Example Output
    现在一切正常。也请查看 prompt_toolkit , 你可以
    创建大量自定义的东西,如图所示 gallery

    关于python - 如何在 Python 中着色用户输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68241694/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com