How to check Python if a string is in a text file and print the string?

What I'm trying to do is check if this line is found in a text file. If so, I want it to print this line, otherwise print the message.

I have already implemented this code:

def check_string(string): w = raw_input("Input the English word: ") if w in open('example.txt').read(): for w.readlines(): print line else: print('The translation cannot be found!') 

I tried to implement this, but got a syntax error.

It says:

invalid syntax in string - for w.readlines ():

Any idea on how to go with this line of code?

+3
source share
2 answers

You should try something like this:

 import re def check_string(): #no need to pass arguments to function if you're not using them w = raw_input("Input the English word: ") #open the file using `with` context manager, it'll automatically close the file for you with open("example.txt") as f: found = False for line in f: #iterate over the file one line at a time(memory efficient) if re.search("\b{0}\b".format(w),line): #if string found is in current line then print it print line found = True if not found: print('The translation cannot be found!') check_string() #now call the function 

If you are looking for exact words, not just a substring, I would suggest using regex here.

Example:

 >>> import re >>> strs = "foo bar spamm" >>> "spam" in strs True >>> bool(re.search("\b{0}\b".format("spam"),strs)) False 
+7
source

Here is a slightly simpler example using the in operator:

 w = raw_input("Input the English word: ") # For Python 3: use input() instead with open('foo.txt') as f: found = False for line in f: if w in line: # Key line: check if `w` is in the line. print(line) found = True if not found: print('The translation cannot be found!') 

If you want to know the position of a string, you can use find() instead of the in operator.

+4
source

Source: https://habr.com/ru/post/976810/


All Articles