是否可以使用python将打印输出保存在字典中? [英] Is it possible to save the print-output in a dict with python?
问题描述
我想知道,是否可以将这段代码的输出保存到字典中(也许这也是错误的数据类型).我还没有编码方面的经验,所以我想不出它可以工作的方式. 我想创建一个字典,其中包含txt.-file的行以及相应行的值.最后,我想创建一个代码,用户可以选择通过输入在行中搜索单词-输出应返回相应的行.有没有人建议?提前致谢!干杯!
I want to know, if it's possible to save the output of this code into a dictionary (maybe it's also the wrong data-type). I'm not expirienced in coding yet, so I can't think of a way it could work. I want to create a dicitionary that has the lines of the txt.-file in it alongside the value of the corresponding line. In the end, I want to create a code, where the user has the option to search for a word in the line through an input - the output should return the corresponding line. Has anyone a suggestion? Thanks in advance! Cheers!
filepath = 'myfile.txt'
with open(filepath) as fp:
line = fp.readline()
cnt = 1
while line:
print("Line {}: {}".format(cnt, line.strip()))
line = fp.readline()
cnt += 1
推荐答案
这应该做到(使用您作为框架提供的代码,只需要多一行即可将其存储在字典中):
This should do it (using the code you provided as a framework, it only takes one extra line to store it in a dictionary):
my_dict={}
filepath = 'myfile.txt'
with open(filepath) as fp:
line = fp.readline()
cnt = 1
while line:
# print("Line {}: {}".format(cnt, line.strip()))
my_dict[str(line.strip())] = cnt
line = fp.readline()
cnt += 1
然后,您可以提示用户输入,如下所示:
Then, you can prompt for user input like this:
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]))
这篇关于是否可以使用python将打印输出保存在字典中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!