基于CSV职称匹配提取文本文件对应行的技术实现需求
Got it, let's tackle this task properly. You need to pull lines from a text file that include any of the job titles (CEO, CTO, COO) stored in a CSV file. Below is the Python implementation you provided, paired with clear input examples and the expected output you're looking for:
First, we'll load all target job titles from the CSV file, then scan each line of the text file to check if it contains any of those titles. Matching lines get collected and outputted.
import csv def extract_matching_lines(text_file, csv_file): # Load job titles from CSV job_titles = [] with open(csv_file, mode='r', encoding='utf-8') as csv_f: csv_reader = csv.reader(csv_f) # Assume each row in CSV holds one job title for row in csv_reader: if row: # Skip empty rows in CSV job_titles.append(row[0].strip()) # Extract lines from text file that contain any job title matching_lines = [] with open(text_file, mode='r', encoding='utf-8') as txt_f: for line in txt_f: stripped_line = line.strip() if any(title in stripped_line for title in job_titles): matching_lines.append(stripped_line) return matching_lines # Run the function if __name__ == "__main__": results = extract_matching_lines("staff.txt", "job_titles.csv") for line in results: print(line)
CSV File (job_titles.csv)
CEO
CTO
COO
Text File (staff.txt)
Liam Carter - Senior Developer
Olivia Reed - CEO
Noah Taylor - Finance Lead
Emma Martinez - CTO
Lucas Anderson - COO
Sophia Garcia - HR Manager
Olivia Reed - CEO
Emma Martinez - CTO
Lucas Anderson - COO
- This code is case-sensitive by default. If you need to match titles regardless of capitalization (e.g., "ceo" or "Ceo"), modify the check to:
if any(title.lower() in stripped_line.lower() for title in job_titles): - If your CSV has a header row or multiple columns, adjust the
job_titles.append(row[0].strip())line to target the correct column index (e.g.,row[1]if titles are in the second column).
内容的提问来源于stack exchange,提问作者Jay

