Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I match a word in a text file using python?

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

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

This code returns even the words that contain 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 the lines which contain "there". Period.

like image 590
Apps Avatar asked Mar 08 '11 04:03

Apps


2 Answers

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 string line and returns true if it finds the regular expression defined in the first parameter, ignoring case with re.I. The ^ character means 'beginning of the line' while the $ character means 'end of the line'. Therefore, the search function will only return true if it matches there preceded by the beginning of the line, and followed by the end of the line, aka isolated on its own.

like image 143
Reznor Avatar answered Sep 29 '22 17:09

Reznor


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

like image 21
jcomeau_ictx Avatar answered Sep 29 '22 17:09

jcomeau_ictx