所以我有一个包含两列的 CSV,其中包含字符串格式的美元金额。head -n 5 file.csv
揭示以下内容:
Title,Distributor Long Name,Wk,Estimated Weekend Gross,Cume,Locs Reported,Avg/Loc,Booking Title #
"=""Zero Dark Thirty""","=""Sony""",4,"24,000,000","29,480,807",2937,"8,172","=""66273"""
"=""Haunted House, A""","=""Open Road""",1,"18,817,000","18,817,000",2160,"8,712","=""71209"""
"=""Gangster Squad""","=""Warner Bros.""",1,"16,710,000","16,710,000",3103,"5,385","=""66556"""
"=""Django Unchained""","=""The Weinstein Company""",3,"11,065,000","125,399,122",3012,"3,674","=""66122"""
这持续了大约 40 行。您会注意到其中两列——“Estimated Weekend Gross”和“Cume”——将它们的值作为字符串。
所以我的问题是,有没有办法只遍历这两列,将字符串值转换为整数row.to_s.gsub(',','').to_i
,然后将这些值覆盖到同一个CSV 中的相应行?
我尝试做这样的事情,但我没有得到格式正确的 CSV ..
File.open('modified.csv', 'w') do |csv|
CSV.foreach('original.csv') do |row|
csv << row[0].to_s.gsub('=','').gsub(', The','')
csv << row[3].to_s.gsub(',','').to_i
csv << row[4].to_s.gsub(',','').to_i
end
end
在做块时我也玩过:headers => :integer
,但它不会让我将值从字符串转换为整数。那么,我错过了什么?我应该存储这些值然后编写一个新的 CSV 还是有更简单的方法?