How to combine a word in a text file using python?

I want to search and match a specific word in a text file.

with open('wordlist.txt', 'r') as searchfile: for line in searchfile: if word in line: print line 

This code even returns words containing substrings of the target word. For example, if the word is “there,” then the search returns “there,” “therefore,” “thereby,” etc.

I want the code to return only lines containing "there." Period.

+4
source share
5 answers

divide the line into tokens: if word in line.split():

+5
source
 import re file = open('wordlist.txt', 'r') for line in file.readlines(): if re.search('^there$', line, re.I): print line 

The re.search function scans the line line and returns true if it finds the regular expression defined in the first parameter, ignoring the case of re.I The ^ symbol means "beginning of line", and the $ symbol means "end of line". Therefore, the search function will return true only if it matches it that precedes the beginning of the line, and it is followed by the end of the line, which itself is isolated.

+5
source

You can always use a regex, something like strings:

 import re with open('wordlist.txt', 'r') as searchfile: for line in searchfile: if re.search( r'\sthere\s', line, re.M|re.I): print line 
  • \sthere\s - any space followed by "there", followed by any space
  • re.I - means case insensitive
  • re.M - it doesn't really matter in this case (since the strings have only 1 \ n)
+1
source

You must use regex. a regular howto expression from Python docs may be a good place to start.

0
source

Check out the re module (regular expressions). re.search with the regex there is what you want.

0
source

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


All Articles