在python中更改用户输入 [英] Change up the user input in python

查看:105
本文介绍了在python中更改用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在编写代码,用户可以使用输入和关键字在词典中进行搜索,以获取相应的行号.关键字实际上在一行中. 使用此代码:

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.

更改的版本:

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?

推荐答案

我的建议是根据上一个问题重建字典,但在循环中,您需要添加两组键值对.一组关键字为句子,值是行号,另一组关键字为行号,值是句子.这样做没有任何风险,因为键是不同的类型:strint.这段代码来自您先前的问题,我添加了几行.

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])

请注意,在您指定可能不存在的行号的地方,我没有进行任何错误检查.我让您自己弄清楚,但是捕获可能的KeyError异常可能很有用.

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.

这篇关于在python中更改用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆