Python读取文本文件每行并按空格分割及变量提取问题求助
Hey there! Let's break down how to solve this problem—extracting those variables from your text file where each line looks like x = variable1 y = variable2 and so on.
Step 1: Read the File and Split Each Line
First, let's handle reading the file and splitting each line into individual parts using Python's built-in open() function. The split() method will automatically handle any extra spaces between elements, which is perfect for your format:
# Open the file in read mode with open('your_input_file.txt', 'r') as file: # Iterate over each line in the file for line in file: # Strip leading/trailing whitespace and split by spaces line_parts = line.strip().split() print(line_parts) # This will show you something like ['x', '=', 'variable1', 'y', '=', 'variable2']
Step 2: Extract Key-Value Pairs
Now that we have each line split into parts, we can loop through the list in steps of 3 (since each key-value pair follows the pattern key = value, which takes up 3 elements in the split list). We'll store these in a dictionary for easy access later:
variables = {} with open('your_input_file.txt', 'r') as file: for line in file: line_parts = line.strip().split() # Loop through the parts in increments of 3 to grab each key-value pair for i in range(0, len(line_parts), 3): # The key is at index i, the value is at index i+2 (skipping the '=') key = line_parts[i] value = line_parts[i + 2] variables[key] = value # Now you can access variables like this: print(variables['x']) # Outputs variable1 print(variables['y']) # Outputs variable2
Why CSV Didn't Work for You
The csv module is great for comma-separated values, but your format uses spaces as separators and includes = signs as part of the structure. By default, csv would treat = as just another piece of data, which is why you were only seeing those symbols. For this kind of custom key-value format, using basic string splitting is simpler and more straightforward.
Bonus: Handling Edge Cases
If some lines might have extra spaces around the = (like x = variable1), the split() method still works because it ignores multiple consecutive spaces. If you need to handle cases where values might contain spaces (e.g., name = John Doe), you'd need a slightly different approach—just let me know if that's a scenario you're dealing with!
内容的提问来源于stack exchange,提问作者user7373790

