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

求助:从文本文件提取特定数据并转换输出格式

Hey there! Let's figure out how to transform your sample.txt data into the format you need. I'll share a few different approaches depending on the tools you're comfortable with:

Python Solution (Cross-Platform & Beginner-Friendly)

This method works on Windows, macOS, and Linux, and it's easy to tweak if your file has multiple entries:

# Open the source file and create the output file
with open('sample.txt', 'r') as infile, open('output.txt', 'w') as outfile:
    # Read all lines, strip whitespace, and skip empty lines
    lines = [line.strip() for line in infile if line.strip()]
    
    # Process data in pairs (name line followed by score line)
    for i in range(0, len(lines), 2):
        # Stop if we don't have a matching score line for a name
        if i + 1 >= len(lines):
            break
            
        name_line = lines[i]
        score_line = lines[i + 1]
        
        # Extract the name (last part after underscores)
        name = name_line.split('_')[-1]
        # Extract the score (parts after "1_details_score_")
        score = '_'.join(score_line.split('_')[3:])
        
        # Write the formatted line to output
        outfile.write(f"{name} = {score}\n")

Shell Script (Quick Terminal Fix for Linux/macOS)

If you prefer using terminal commands, awk can handle this in one line:

awk -F '_' 'NR%2==1{name=$NF} NR%2==0{print name " = " substr($0, index($0,$4))}' sample.txt > output.txt
  • NR%2==1 captures the name from odd-numbered lines (your 1_name_JACK lines)
  • NR%2==0 takes the score portion from even-numbered lines and formats the output

Ruby Solution (Tailored for Ruby Developers)

Since you're working with Ruby, here's a clean Ruby script to do the job:

File.open('output.txt', 'w') do |outfile|
  # Read and clean up lines from the input file
  lines = File.readlines('sample.txt').map(&:strip).reject(&:empty?)
  
  # Process lines two at a time
  lines.each_slice(2) do |name_line, score_line|
    name = name_line.split('_').last
    score = score_line.split('_')[3..].join('_')
    outfile.puts "#{name} = #{score}"
  end
end

All of these will generate an output.txt file with your desired JACK = 1_1_1_1_1_1_1 format. Just pick the one that fits your workflow best!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:30:31