【问题标题】:Python autocomplete user input [closed]Python自动完成用户输入[关闭]
【发布时间】:2014-01-25 04:18:00
【问题描述】:

我有一个团队名称列表。假设他们是

teamnames=["Blackpool","Blackburn","Arsenal"]

在程序中,我询问用户他想与哪个团队合作。我希望 python 自动完成用户的输入,如果它匹配一个团队并打印它。

因此,如果用户输入“Bla”并按下 enter,则应将 Blackburn 团队自动打印到该空间并用于其余代码。比如;

您的选择:Bla(用户写“Bla”并按enter

应该是什么样子

您的选择:布莱克本(程序完成单词的其余部分)

【问题讨论】:

  • 那么到目前为止,您尝试过什么,您也应该将其包括在内。让我们看看你到现在为止的努力。你到底在哪里卡在你的代码中。
  • 为什么这个问题跑题了?给定可能的输入列表,它似乎明确要求如何在 python 中实现“输入”完成(如制表符完成)。

标签: python string printing autocomplete sentence


【解决方案1】:
teamnames=["Blackpool","Blackburn","Arsenal"]

user_input = raw_input("Your choice: ")

# You have to handle the case where 2 or more teams starts with the same string.
# For example the user input is 'B'. So you have to select between "Blackpool" and
# "Blackburn"
filtered_teams = filter(lambda x: x.startswith(user_input), teamnames)

if len(filtered_teams) > 1:
    # Deal with more that one team.
    print('There are more than one team starting with "{0}"'.format(user_input))
    print('Select the team from choices: ')
    for index, name in enumerate(filtered_teams):
        print("{0}: {1}".format(index, name))

    index = input("Enter choice number: ")
    # You might want to handle IndexError exception here.
    print('Selected team: {0}'.format(filtered_teams[index]))

else:
    # Only one team found, so print that team.
    print filtered_teams[0]

【讨论】:

    【解决方案2】:

    这取决于您的用例。如果您的程序是基于命令行的,您至少可以通过使用readline 模块并按TAB 来做到这一点。自 Doug Hellmanns PyMOTW 以来,此链接还提供了一些很好解释的示例。如果您通过 GUI 进行尝试,则取决于您使用的 API。在这种情况下,您需要提供更多详细信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-31
      • 2021-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多