Search code examples
pythonif-statementdirectorypython-3.8listdir

Python: How to use list of keywords to search for a string in a text


So I'm writing a program that loops through multiple .txt files and searches for any number of pre-specified keywords. I'm having some trouble finding a way to pass through the keywords list to be searched for.

The code below currently returns the following error:

TypeError: 'in <string>' requires string as left operand, not list

I'm aware that the error is caused by the keyword list but I have no idea how to input a large array of keywords without it running this error.

Current code:

from os import listdir

keywords=['Example', 'Use', 'Of', 'Keywords']
 
with open("/home/user/folder/project/result.txt", "w") as f:
    for filename in listdir("/home/user/folder/project/data"):
        with open('/home/user/folder/project/data/' + filename) as currentFile:
            text = currentFile.read()
            #Error Below
            if (keywords in text):
                f.write('Keyword found in ' + filename[:-4] + '\n')
            else:
                f.write('No keyword in ' + filename[:-4] + '\n')

The error is indicated in line 10 in the above code under the commented section. I'm unsure as to why I can't call a list to be able to search for the keywords. Any help is appreciated, thanks!


Solution

  • You could replace

    if (keywords in text):
       ...
    

    with

    if any(keyword in text for keyword in keywords):
       ...