Change up the user input in python

2019-08-20 23:05发布

I'm currently working on a code, where the user is able to search through a dictionary with an input and keywords to get the corresponding line number in return. The keywords are actually in the line. Using this code:

usr_in = input('enter text to search: ') 

print('That text is found at line(s) {}'.format
               ( [v for k,v in my_dict.items() if usr_in in k]))

Now I also want to have another user input right after this one, where the user can type in the number of the line and in return the whole line shows up as an output. I've tried to alter the code above, but without results.

The altered version:

usr_in_line = input('Please enter the line number: ')

print('Corresponding Line {}'.format(
         [k for v,k in my_dict.items() if usr_in_line in v]))

The whole code can be found here: Is it possible to save the print-output in a dict with python?

2条回答
Summer. ? 凉城
2楼-- · 2019-08-20 23:50

A suggestion I have is to rebuild your dictionary from the previous question but in the loop, you'd add two sets of key-value pairs. One set where the key is the sentence and the value is the line number and another set were the key is the line number and the value is the sentence. There wouldn't be any risk in doing so because the keys are different types: str and int. This code comes from your previous question and I've added a couple of lines.

my_dict={} 
filepath = 'myfile.txt' 
with open(filepath) as fp: 
    line = fp.readline() 
    cnt = 1 
    while line: 
        # print("Line {}: {}".format(cnt, line.strip()))
        s = str(line.strip()) # Added
        my_dict[cnt] = s # Added
        my_dict[s] = cnt
        line = fp.readline() 
        cnt += 1

You can now not only ask for the word search, but you now ask for the line:

usr_in = input('enter text to search: ')
print('That text is found at line(s) {}'.format([v for k,v in my_dict.items() if usr_in in k]))

line_in = int(input('enter line: ')) 
print('The line is: {}'.format(my_dict[line_in])

Note that I didn't do any error checking where you specify a line number that may not exist. I'll leave that to you to figure out, but catching a possible KeyError exception may be useful.

查看更多
相关推荐>>
3楼-- · 2019-08-20 23:50

Try using default parameters into a function controlling the lookup

Optionally, if you doing input from the command line, checkout argparse

Those things together should give you a default value for input, and an optional flag that can be used in command line, to print out the entire line.

Honestly, Defaults are the best way to provide behaviour on a function like this

查看更多
登录 后发表回答