如何用Python在文本文件中筛选Male且来自Canada的人员全量信息
Solution: Filter Male Canadian Entries from a Text File
First, let's assume your input text file (let's call it people.txt) has each person's details on a single line, with fields separated by a consistent delimiter—like a comma. For example:
Alex,Baldwin,Engineer,1985-03-12,Male,Canada
Jane,Smith,Teacher,1990-07-22,Female,Canada
Gary,Allen,Designer,1978-11-05,Male,Canada
Mike,Johnson,Doctor,1982-04-18,Male,USA
Here's a straightforward Python program that meets all your requirements—no regex, no external input, just plain line-by-line processing:
# Define the file path (adjust this to your actual file location) FILE_PATH = "people.txt" # Fixed filter criteria as requested TARGET_GENDER = "Male" TARGET_NATIONALITY = "Canada" # Expected field order: First Name, Last Name, Occupation, Date of Birth, Gender, Nationality EXPECTED_FIELDS = 6 try: with open(FILE_PATH, 'r') as file: for line_num, line in enumerate(file, start=1): # Clean up the line and skip empty ones cleaned_line = line.strip() if not cleaned_line: continue # Split the line into individual fields person_details = cleaned_line.split(',') # Skip lines that don't have the right number of fields to avoid errors if len(person_details) != EXPECTED_FIELDS: print(f"Skipping invalid line {line_num}: {cleaned_line}") continue # Unpack the fields into readable variables first_name, last_name, occupation, dob, gender, nationality = person_details # Check if the entry matches our fixed criteria if gender == TARGET_GENDER and nationality == TARGET_NATIONALITY: # Print the full details in a user-friendly format print(f"Matched Entry:\nName: {first_name} {last_name}\nOccupation: {occupation}\nDate of Birth: {dob}\nGender: {gender}\nNationality: {nationality}\n---") except FileNotFoundError: print(f"Error: Could not find the file {FILE_PATH}. Double-check the path!") except Exception as e: print(f"An unexpected issue occurred: {str(e)}")
Key Notes About This Implementation:
- No External Input: All filter rules and the file path are hardcoded exactly as you asked.
- Safe File Handling: Uses a
withstatement to automatically close the file after processing, which is the standard Python best practice. - Error Prevention: Skips empty lines and entries with missing/extra fields to avoid index errors or broken output.
- Readable Output: Formats matching entries clearly instead of just printing raw line text.
If your text file uses a different delimiter (like tabs or semicolons), just replace split(',') with split('\t') or split(';') to match your file's format.
内容的提问来源于stack exchange,提问作者Sarah Miller
相关产品推荐
相关产品推荐

