如何用Ruby拆分CSV单元格数据并转换为指定格式数组
How to Process the CSV-like File and Download Images in Ruby
Here's a straightforward, step-by-step solution to convert your input into the desired array format and download the corresponding JPG files using Ruby:
Step 1: Break Down the Task
We need to:
- Split rows containing multiple URLs into separate entries
- Emphasize the
itemIdandurlfields for split rows (using**wrapping) - Download each URL as a JPG file to your local directory
Step 2: Ruby Script Implementation
First, ensure Ruby is installed (it comes pre-installed on most macOS/Linux systems; Windows users can grab it from the official Ruby website). Create a new file named process_and_download.rb with this code:
require 'open-uri' # Replace with your input file path (e.g., './my_input.txt') INPUT_FILE_PATH = 'input.txt' # Read all lines from the input file, stripping trailing newlines lines = File.readlines(INPUT_FILE_PATH).map(&:chomp) # Process and print the header row header = lines.first.split('|') puts "[#{header.join(',')}]" # Process each data line lines[1..-1].each do |line| # Split the line into its core components using | as the delimiter item_id, urls_str, name, type = line.split('|') # Split the URL string into individual URLs using commas urls = urls_str.split(',') urls.each_with_index do |url, index| # Format the row: add emphasis if there are multiple URLs in the original row row_elements = if urls.size > 1 ["**#{item_id}**", "**#{url}**", name, type] else [item_id, url, name, type] end # Print the formatted row to the console puts "[#{row_elements.join(',')}]" # Download the JPG file begin # Generate a unique filename to avoid overwriting files filename = urls.size > 1 ? "#{item_id}_#{index + 1}.jpg" : "#{item_id}.jpg" # Save the downloaded file to your local directory File.open(filename, 'wb') do |file| file.write(URI.open(url).read) end puts "✅ Downloaded: #{filename}" rescue StandardError => e puts "❌ Failed to download #{url}: #{e.message}" end end end
Step 3: Run the Script
- Save your input content into a file named
input.txt(or update theINPUT_FILE_PATHvariable to match your file's location) - Open your terminal/command prompt, navigate to the folder where the script and input file are located
- Run the script with:
ruby process_and_download.rb
What Happens Next?
- The script will print the formatted array rows to your console exactly as you requested
- It will download all JPG files to the same directory as the script. For rows with multiple URLs, files will be named like
3_1.jpgand3_2.jpgto avoid overwriting.
Example Console Output
[itemId,url,name,type] [1,urlA,nameA,typeA] [2,urlB,nameB,typeB] [**3**,**urlC**,nameC,typeC] [**3**,**urlD**,nameC,typeC] [4,urlE,nameE,typeE] ✅ Downloaded: 1.jpg ✅ Downloaded: 2.jpg ✅ Downloaded: 3_1.jpg ✅ Downloaded: 3_2.jpg ✅ Downloaded: 4.jpg
内容的提问来源于stack exchange,提问作者shnog
相关产品推荐
相关产品推荐

