Python按规则分割文件行 生成以特定字段为键的字典
Parsing Text into Target Dictionary
Got it, let's tackle this problem. You need to convert that structured text into a dictionary where each key is the first field of an entry's starting line (like AFA, MKE, or KTE), and the value includes all lines belonging to that entry—including any following lines starting with S.
Step-by-Step Approach
- Initialize an empty dictionary to store results, plus a variable to track the current entry's key.
- Iterate over each line in the text (whether read from a file or a string).
- Skip any empty lines to avoid errors.
- For lines not starting with "S": this is the start of a new entry. Extract the first word as the key, then initialize a list in the dictionary for this key with the current line.
- For lines starting with "S": add this line to the list of the most recent entry we processed.
Python Code Implementation
def parse_entry_text(text): entry_dict = {} current_key = None for line in text.splitlines(): cleaned_line = line.strip() if not cleaned_line: continue # Skip empty lines if not cleaned_line.startswith("S"): # New entry: extract the first field as the key key = cleaned_line.split()[0] current_key = key entry_dict[key] = [cleaned_line] else: # Append S-line to the current entry if current_key is not None: entry_dict[current_key].append(cleaned_line) return entry_dict # Example usage with your sample text sample_input = """AFA MT 0 0 1.22 259 169 FOD 0 50.01 1.3 1.370 0.00 -0.02 1.78 0 0.0 S 2 50.620 1.960 2.452 0.00 -0.49 0.31 MKE MS 0 0 4.22 256 149 MDO 1 30.00 1.4 2.370 3.00 -0.52 4.82 0 0.0 KTE KL 0 0 1.22 259 169 FID 0 10.01 2.0 2.470 1.00 -0.12 0.78 1 1.0 S 3 70.610 1.960 2.52 0.00 -0.19 0.41""" # Parse and display the result result = parse_entry_text(sample_input) for key, lines in result.items(): print(f"Key: {key}") for line in lines: print(f" {line}")
Example Output
Key: AFA AFA MT 0 0 1.22 259 169 FOD 0 50.01 1.3 1.370 0.00 -0.02 1.78 0 0.0 S 2 50.620 1.960 2.452 0.00 -0.49 0.31 Key: MKE MKE MS 0 0 4.22 256 149 MDO 1 30.00 1.4 2.370 3.00 -0.52 4.82 0 0.0 Key: KTE KTE KL 0 0 1.22 259 169 FID 0 10.01 2.0 2.470 1.00 -0.12 0.78 1 1.0 S 3 70.610 1.960 2.52 0.00 -0.19 0.41
Notes
- If you're reading from a file instead of a string, replace the
sample_inputwith:with open("your_file.txt", "r") as f: sample_input = f.read() - This handles entries with or without subsequent "S" lines, and skips any empty lines in the input.
内容的提问来源于stack exchange,提问作者user3650827
相关产品推荐
相关产品推荐

