Python autocomplete user input
Asked Answered
M

3

12

I have a list of teamnames. Let's say they are

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

In the program I ask the user which team he would like to do stuff with. I want python to autocomplete the user's input if it matches a team and print it.

So if the user writes "Bla" and presses enter, the team Blackburn should automatically be printed in that space and used in the rest of the code. So for example;

Your choice: Bla (User writes "Bla" and presses enter)

What it should look like

Your Choice: Blackburn (The program finishes the rest of the word)

Mehalick answered 7/1, 2014 at 13:3 Comment(3)
So what have you tried till now, you should include that too. Let us see your efforts till now. Where are you stuck exactly in your code.Preconceive
Why is this question off topic? it seems to clearly ask for how to implement "enter"-completion (like tab-completion) in python given a list of possible inputs.Windburn
it is not off topic, it simply doesn't show any effort.Searching
M
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]
Modicum answered 7/1, 2014 at 13:16 Comment(0)
P
1

That depends on your usecase. If your program is commandline based, you can do that at least by using the readline module and pressing TAB. This link also provides some well explained examples on that since its Doug Hellmanns PyMOTW. If you are trying that via a GUI it depends on the API you are using. In that case you need to deliver some more details please.

Pilloff answered 7/1, 2014 at 13:20 Comment(0)
P
0

This does not exactly behave as you described, but you could use the inquirer module (GitHub, installable with pip install inquirer)

This module provides several command line interface tools that you may use. The most straightforward is the inquirer.list_input function, that works like this :

import inquirer
team = inquirer.list_input("Choose team", choices=["Blackpool","Blackburn","Arsenal"])

Result (use up and down arrows to select entry):

Screen recording of the resulting prompt

You may also use the following optional parameters

  • carousel: if True, loop back at the start when the down key is pressed on the last entry
  • default: Select a default value different from the first entry

If your list of possible inputs is very long, you may use the inquirer.text function as a drop-in replacement for input, with a custom autocomplete function.


def team_completer(text, state):
    teams = ["Blackpool","Blackburn","Arsenal"]
    candidates = [team for team in teams if team.startswith(text)]
    if candidates:
        return candidates[state % len(candidates)]

team = inquirer.text("Enter Team:", autocomplete=team_completer)

You can then use the TAB key to autocomplete results as you type. You may want to also define a validator function to ensure only a valid team is chosen

def validator(_, text):
    if text in ["Blackpool","Blackburn","Arsenal"]:
        return True
    raise inquirer.errors.ValidationError("", reason=f'Team "{text}" do not exist')

team = inquirer.text("Enter Team:", autocomplete=team_completer, validate=validator)
 

Note that the validation message may not be displayed correctly on Windows though.

Pleach answered 5/9 at 12:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.