将文本文件转换为字典列表:Python脚本实现与优化咨询
Fixing Your Script to Convert Text to a List of Dictionaries
Let's get your script working to produce the list of dictionaries you need! First, let's break down the issues in your original code, then walk through the corrected version.
Issues in the Original Script
- You tried incrementing
rowcountbut never defined it first (and it wasn't even needed for your goal!) - The condition
if row[0] == ' ' in row:is incorrect—you just need to check if the line starts with a space - You only built a single dictionary instead of a list of dictionaries
- The last group of items in your text file wouldn't get added to the result, since the loop ends without handling it
Corrected Script
dict_list = [] current_key = None current_values = [] # Use a context manager to safely open/close the file with open('/home/asha/Desktop/test.txt', 'r') as f: for line in f: # Clean up the line and skip empty ones cleaned_line = line.strip() if not cleaned_line: continue # This line is a new category (key) if not line.startswith(' '): # If we have an existing key/values, add them to the list first if current_key is not None: dict_list.append({current_key: current_values}) current_values = [] # Set the new category as our current key current_key = cleaned_line else: # This line is an item under the current category—add to values current_values.append(cleaned_line) # Don't forget to add the final category after the loop ends if current_key is not None and current_values: dict_list.append({current_key: current_values}) # Print the result print(dict_list)
How This Works
- Context Manager (
withstatement): This ensures the file is automatically closed when we're done, which is safer than manually opening/closing. - Tracking State: We keep track of the current category (
current_key) and its items (current_values) as we loop through each line. - Handling New Categories: When we hit a line that doesn't start with a space (a new category), we first add the previous category and its items to our list, then reset for the new category.
- Final Cleanup: After the loop finishes, we add the last category to the list—since the loop won't trigger that step on its own.
- Clean Lines: Using
strip()removes extra whitespace and newlines, and we skip empty lines to avoid clutter.
Example Output
Using your sample text file, the script will output something like this:
[ { "Time": [ "NtGetTickCount", "NtQueryPerformanceCounter", "NtQuerySystemTime", "NtQueryTimerResolution", "NtSetSystemTime", "NtSetTimerResolution", "RtlTimeFieldsToTime", "RtlTimeToTime" ] }, { "System informations": [ "NtQuerySystemInformation", "NtSetS..." ] } ]
内容的提问来源于stack exchange,提问作者user9279273
相关产品推荐
相关产品推荐

