如何使用Python在文本文件中查找指定关键词?附示例
Hey there! Let's tackle this keyword search task for your text file in Python. Here's a simple, efficient way to get the exact result you're looking for:
Python Text File Keyword Search Implementation
First, let's walk through the approach: we'll read your text file's content, check which of your target keywords are present, then output the matches as a space-separated string.
Here's the full code you can use:
# Our predefined list of keywords keywords = ['monday', 'tuesday', 'wednesday', 'thursday'] # Read the text file (make sure to replace 'your_file.txt' with your actual file path) with open('your_file.txt', 'r') as file: # Convert content to lowercase to handle case variations (like 'Tuesday' instead of 'tuesday') text_content = file.read().lower() # Filter out keywords that aren't in the text content matched_keywords = [keyword for keyword in keywords if keyword in text_content] # Print the result as space-separated keywords print(' '.join(matched_keywords))
Let's break down each part:
- Keyword Setup: We start with your exact keyword list, no changes needed here.
- File Reading: Using a
withstatement is Python best practice—it automatically closes the file once we're done, so you don't have to worry about resource leaks. Converting the content to lowercase ensures we catch matches regardless of capitalization (perfect if your text has things like "Tuesday" instead of all lowercase). - Matching Logic: The list comprehension quickly checks each keyword against the text content, keeping only the ones that show up.
- Output: Joining the matched list into a string gives you the clean
tuesday wednesdayoutput you expect for your sample text.
Quick tweak if needed:
If you want a strict case-sensitive search (only match exact lowercase keywords), just remove the .lower() when reading the file content.
内容的提问来源于stack exchange,提问作者lol
相关产品推荐
相关产品推荐

