0

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
  • 1
    So what is it you're asking for? How to search through your text or how to save your text to a dictionary? Commented Mar 14, 2018 at 20:28

2 Answers 2

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]))
Sign up to request clarification or add additional context in comments.

12 Comments

This assumes that you are entering in the exact sentence to search for. This doesn't handle a partial search, which is what I'm assuming the OP actually wants. Not entering in the exact string to search for would not generate any matches and the code would throw KeyError exception.
Thank you, but I'm sitll getting an error: line 59, in <listcomp> [v for k,v in line_dict.items() if usr_in in k])) TypeError: argument of type 'int' is not iterable
in your with open loop, try replacing my_dict[line.strip()] = cnt with my_dict[str(line.strip())] = cnt and see if that helps
Now it works, but I don't always getting a line in return of my imput. Working: enter text to search: moon That text is found at line(s) [8] Not working: enter text to search: dream That text is found at line(s) [] Can I solve this somehow?
@StrikeX To help with the case insensitivity, it's common to convert the search query and a line in your text both to lower case to normalize the casing prior to comparison. Only do this when you're searching, not when you're actually entering the text in the dictionary. This way if you want to display the actual text entered, it's the true text and not the converted lowercase form. Replace the line in the comprehension with: [v for k,v in my_dict.items() if usr_in.lower() in k.lower()]
|
1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.