You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Python 3脚本实现两个文本文件的横向拼接?

实现JASCO光谱文件的横向拼接

Got it, let's fix this to get the horizontal concatenation you need for your JASCO spectral files. The original script just appends one file after another, but we need to pair corresponding header entries and XY data points side by side instead.

思路分析

Your JASCO files have two distinct sections:

  1. A header with key-value pairs (like TITLE, DATE, FIRSTY) that follow the same order in both files.
  2. XYDATA entries, where each data point is a set of three values (wavelength, CD, HT) that need to be paired across files.

The solution will:

  • Parse each file to extract header key-value pairs and XY data points.
  • Merge corresponding header lines and XY data lines from both files into single lines.

修改后的Python脚本

def horizontal_concat_files(input_filenames, output_filename):
    # Define the fixed order of header keys for JASCO files
    header_keys = [
        'TITLE', 'DATA TYPE', 'ORIGIN', 'OWNER', 'DATE', 'TIME',
        'SPECTROMETER/DATA SYSTEM', 'RESOLUTION', 'DELTAX', 'XUNITS',
        'YUNITS', 'HT[V]', 'FIRSTX', 'LASTX', 'NPOINTS', 'FIRSTY',
        'MAXY', 'MINY', 'XYDATA'
    ]
    
    file_data = []
    for fname in input_filenames:
        with open(fname, 'r') as f:
            content = f.read()
            tokens = content.split()
            key_values = []
            current_key_pos = 0
            token_idx = 0
            
            # Extract header key-value pairs
            while current_key_pos < len(header_keys) and token_idx < len(tokens):
                current_key = header_keys[current_key_pos]
                key_parts = current_key.split()
                
                # Check if current token(s) match the header key
                if tokens[token_idx:token_idx+len(key_parts)] == key_parts:
                    token_idx += len(key_parts)
                    value_parts = []
                    
                    # Collect values until next header key is found
                    next_key_pos = current_key_pos + 1
                    while token_idx < len(tokens):
                        if next_key_pos < len(header_keys):
                            next_key = header_keys[next_key_pos]
                            next_key_parts = next_key.split()
                            if tokens[token_idx:token_idx+len(next_key_parts)] == next_key_parts:
                                break
                        value_parts.append(tokens[token_idx])
                        token_idx += 1
                    
                    key_values.append((current_key, ' '.join(value_parts)))
                    current_key_pos += 1
            
            # Extract XY data points (each point is 3 values: X, CD, HT)
            xy_points = []
            while token_idx + 2 < len(tokens):
                point = ' '.join(tokens[token_idx:token_idx+3])
                xy_points.append(point)
                token_idx += 3
            
            file_data.append((key_values, xy_points))
    
    # Write the concatenated output
    with open(output_filename, 'w') as outfile:
        # Merge header lines
        for idx in range(len(file_data[0][0])):
            key1, val1 = file_data[0][0][idx]
            key2, val2 = file_data[1][0][idx]
            
            line_components = []
            line_components.append(f"{key1} {val1}" if val1 else key1)
            line_components.append(f"{key2} {val2}" if val2 else key2)
            
            outfile.write(' '.join(line_components) + '\n')
        
        # Merge XY data lines
        max_xy_lines = max(len(file_data[0][1]), len(file_data[1][1]))
        for idx in range(max_xy_lines):
            line_parts = []
            if idx < len(file_data[0][1]):
                line_parts.append(file_data[0][1][idx])
            if idx < len(file_data[1][1]):
                line_parts.append(file_data[1][1][idx])
            outfile.write(' '.join(line_parts) + '\n')

# Usage example
horizontal_concat_files(['file1.txt', 'file2.txt'], 'concatenated_output.txt')

脚本说明

  1. Header Parsing: We use the predefined header_keys list to accurately extract each key and its corresponding value from both files, even for keys with spaces like SPECTROMETER/DATA SYSTEM.
  2. XY Data Extraction: After processing the header, we split the remaining tokens into groups of three (one data point per group) to match the structure of JASCO spectral data.
  3. Merging: We iterate through the header key-value pairs and XY data points, merging corresponding entries from both files into single lines for the output.

如何使用

Just call the horizontal_concat_files function with your input filenames as a list and the desired output filename. For your case, the example usage will generate the exact output format you shared.

内容的提问来源于stack exchange,提问作者Sam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:08:17