如何用Python提取output.txt中指定字符后的值并按格式输出
Hey there! Let's walk through how to use dictionaries to extract and format those personal details from your output.txt file. Here's a straightforward approach tailored to your needs:
Solution Using Dictionaries
Core Idea
We’ll use a dictionary to temporarily store each person’s four details as we parse the file. Once we’ve collected all four fields for a person, we’ll format them into the required string format, add it to our results list, then reset the dictionary to capture the next person’s info. This keeps our data organized and makes it easy to validate when we have a complete set of details.
Step-by-Step Breakdown
- Initialize variables: We’ll need an empty list to hold all formatted person strings, and an empty dictionary to track the current person’s details as we parse lines.
- Define target fields: List out the exact field names we’re looking for (since your file has "First name", "Last Name", etc., we’ll match these exactly).
- Parse the file line by line: For each line, check if it starts with one of our target fields. If it does, extract the value and add it to the dictionary.
- Check for complete person data: Every time the dictionary has all four fields, we’ll format the string, add it to our results, and reset the dictionary for the next person.
- Combine results: Finally, join all the formatted person strings into a single output string.
Full Code Example
# Read the file content (you mentioned you already have this part, but including for completeness) with open('output.txt', 'r') as file: lines = file.readlines() # Initialize storage for results and current person's details formatted_output = [] current_person = {} # Define the fields we need to extract (matches the exact labels in your file) required_fields = ["First name", "Last Name", "Age", "Country"] for line in lines: line = line.strip() # Skip empty lines or irrelevant text that doesn't match our fields if not line or not any(field in line for field in required_fields): continue # Split the line into field name and value (assuming format like "First name: Petar") field_name, value = line.split(':', 1) field_name = field_name.strip() value = value.strip() # Add the value to our current person dictionary if field_name in required_fields: current_person[field_name] = value # Check if we've collected all four fields for this person if len(current_person) == len(required_fields): # Format the details into the required string: "First Last Age Country" person_string = f"{current_person['First name']} {current_person['Last Name']} {current_person['Age']} {current_person['Country']}" formatted_output.append(person_string) # Reset the dictionary to start collecting the next person current_person = {} # Combine all formatted strings into the final output final_result = ' '.join(formatted_output) print(final_result)
Key Notes
- Handling irrelevant text: The code skips any lines that don’t contain one of our target fields, so random descriptions won’t interfere with extraction.
- Flexible field order: Even if the fields appear in a different order for each person (e.g., Age first, then Country), the dictionary will still collect all four before formatting.
- File safety: Using
with open(...)ensures the file is properly closed after reading, which is good practice.
内容的提问来源于stack exchange,提问作者Milister




