Skip to content Skip to sidebar Skip to footer

How To Search A Text File For A Specific Word In Python

I want to find words in a text file that match words stored in an existing list called items, the list is created in a previous function and I want to be able to use the list in th

Solution 1:

You can use regexp the following way:

    >>> import re
    >>> words=['car','red','woman','day','boston']
    >>> word_exp='|'.join(words)
    >>> re.findall(word_exp,'the red car driven by the woman',re.M)
    ['red', 'car', 'woman']

The second command creates a list of acceptable words separated by "|". To run this on a file, just replace the string in 'the red car driven by the woman' for open(your_file,'r').read().


Solution 2:

This may be a bit cleaner. I feel class is an overkill here.

def createlist():
    items = []
    with open('words.txt') as input:
        for line in input:
            items.extend(line.strip().split(','))
    return items

print(createlist())
# store the list
word_list = createlist()

with open('file.txt') as f:
    # split the file content to words (first to lines, then each line to it's words)
    for word in (sum([x.split() for x in f.read().split('\n')], [])):
        # check if each word is in the list
        if word in word_list:
            # do something with word
            print word + " is in the list"
        else:
            # word not in list
            print word + " is NOT in the list"

Solution 3:

There is nothing like Regular expressions in matching https://docs.python.org/3/howto/regex.html

items=['one','two','three','four','five'] #your items list created previously
import re
file=open('text.txt','r') #load your file
content=file.read() #save the read output so the reading always starts from begining
for i in items:
    lis=re.findall(i,content)
    if len(lis)==0:
        print('Not found')
    elif len(lis)==1:
        print('Found Once')
    elif len(lis)==2:
        print('Found Twice')
    else:
        print('Found',len(lis),'times')

Post a Comment for "How To Search A Text File For A Specific Word In Python"