Search file for multiple keywords in listfile Python

  • 1 year ago
Comment

ChatGPT
1 / 1

To search for multiple keywords in a file using a list of keywords in Python, you can read the file line by line and check each line for the presence of any of the keywords. Here's a simple example of how you could do this:

python
def search_keywords_in_file(file_path, keywords):
found_lines = []

with open(file_path, 'r') as file:
for line_number, line in enumerate(file, start=1):
if any(keyword in line for keyword in keywords):
found_lines.append((line_number, line.strip()))

return found_lines

# Example usage
file_path = 'path_to_your_file.txt'
keywords = ['keyword1', 'keyword2', 'keyword3']

found_lines = search_keywords_in_file(file_path, keywords)

if found_lines:
for line_number, line in found_lines:
print(f"Found keyword(s) on line {line_number}: {line}")
else:
print("No keywords found in the file.")

Replace 'path_to_your_file.txt' with the path to the file you want to search in, and ['keyword1', 'keyword2', 'keyword3'] with your list of keywords.

This code defines a function search_keywords_in_file that takes a file path and a list of keywords as inputs. It reads each line of the file and checks if any of the keywords are present in the line. If a keyword is found in a line, the line number and the line content are added to the found_lines list. Finally, the script prints out the lines where the keywords were found.

Keep in mind that this is a simple example and doesn't consider various edge cases. Depending on your specific requirements and the size of the file, you might need to optimize the code or handle more complex scenarios.