Is it possible to save the print-output in a dict with python?

醉酒当歌 提交于 2019-12-11 16:55:38

问题


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

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



回答2:


For storing the line string value as key in dictionary and line number as value, you can try something like:

filepath = 'myfile.txt' 

result_dict = {}
with open(filepath) as fp:  
    for line_num, line in enumerate(fp.readlines()):
        result_dict[line.strip()] = line_num+1

Or, using dictionary comprehension, above code can be:

filepath = 'myfile.txt' 

with open(filepath) as fp:  
    result_dict = {line.strip(): line_num+1 
                        for line_num, line in enumerate(fp.readlines())}

Now to search and return all the lines with words:

search_result = [{key: value} for key, value in result_dict.items() 
                                  if search_word in key]


来源:https://stackoverflow.com/questions/49287058/is-it-possible-to-save-the-print-output-in-a-dict-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!