如何用Python将单行多空格分隔的向量数据逐行写入TXT文件?
Got it, let's solve this problem step by step. You're dealing with a line full of vector entries separated by exactly 13 spaces, and you want each vector on its own line in a new text file. Here's how to handle this with Python:
Basic Solution (Exact 13 Spaces as Separator)
If you're certain the vectors are split by exactly 13 spaces, you can use Python's built-in string split() method with the precise separator:
# Open input and output files in one go (cleaner resource management) with open('your_input_file.txt', 'r') as infile, open('output_vectors.txt', 'w') as outfile: # Iterate over each line in the input file (works even if there are multiple such lines) for line in infile: # Split the line using 13 spaces as the delimiter vector_list = line.split(' ' * 13) # Filter out empty strings (in case there are leading/trailing spaces in the line) cleaned_vectors = [vec.strip() for vec in vector_list if vec.strip()] # Write each vector to a new line in the output file for vec in cleaned_vectors: outfile.write(f"{vec}\n")
Robust Solution (Handles 13+ Spaces)
If there's a chance the separator might be 13 or more consecutive spaces (e.g., typos where extra spaces were added), use regular expressions to split more flexibly:
import re with open('your_input_file.txt', 'r') as infile, open('output_vectors.txt', 'w') as outfile: for line in infile: # Split on 13 or more consecutive spaces vector_list = re.split(r'\s{13,}', line.strip()) # Remove any empty entries from the split result cleaned_vectors = [vec for vec in vector_list if vec] for vec in cleaned_vectors: outfile.write(f"{vec}\n")
How This Works:
- The
withstatement ensures files are properly closed after processing, no need to manually callclose(). split(' ' *13)targets the exact 13-space separator you mentioned.- The regex
\s{13,}matches 13 or more whitespace characters (swap with{13,}if you only want to match spaces, not tabs/newlines). - The cleaning step removes any empty strings that might come from leading/trailing separators in the original line.
Just replace your_input_file.txt with your actual input filename, and output_vectors.txt with your desired output filename, and this should do exactly what you need.
内容的提问来源于stack exchange,提问作者gradstudent61

