Skip to content

Instantly share code, notes, and snippets.

@tomisacat
Created September 4, 2017 06:31
Show Gist options
  • Save tomisacat/352a0aa9d6dec624e75ba85fe293535c to your computer and use it in GitHub Desktop.
Save tomisacat/352a0aa9d6dec624e75ba85fe293535c to your computer and use it in GitHub Desktop.
Process .csv file with Ruby
#!/usr/bin/env ruby
require 'csv'
Wechat = "微信"
Alipay = "支付宝"
QQpay = "qq钱包"
# 店铺
class Merchant
attr_accessor :wechat_pay_less_than_5_count # 微信支付金额少于5的笔数
attr_accessor :merchant_name # 店铺名称
attr_accessor :wechat
attr_accessor :alipay
attr_accessor :qqpay
def initialize(name)
@wechat_pay_less_than_5_count = 0
@merchant_name = name
@wechat = Payment.new(Wechat)
@alipay = Payment.new(Alipay)
@qqpay = Payment.new(QQpay)
end
end
# 支付方式
class Payment
attr_accessor :type #微信,支付宝2.0,qq钱包
attr_accessor :count # 笔数
attr_accessor :settlement_amount # 结算金额
attr_accessor :service_charge # 手续费
def initialize(type)
@type = type
@count = 0
@settlement_amount = 0
@service_charge = 0
end
end
# 最终结果
# {
# "大丰精品超市" => { Merchant } => [Payment]
# }
Result = {}
# 列号从 0 开始,因此交易日期是第 0 列
# 第 3 列:支付方式
# 第 4 列:商铺名称(商品名)
# 第 18 列:手续费
# 第 20 列:结算金额
# 第 12 列:交易金额,如果支付方式是微信,则用它统计金额小于5的笔数
CSV.open('details.csv', 'r').each do |row|
merchant_name = row[4]
merchat = nil
if Result[merchant_name] == nil
merchant = Merchant.new(merchant_name)
Result[merchant_name] = merchant
else
merchant = Result[merchant_name]
end
payment_type = row[3]
if payment_type.start_with?(Wechat)
merchant.wechat.count += 1
merchant.wechat.settlement_amount += row[20].to_f
merchant.wechat.service_charge += row[18].to_f
if row[12].to_f < 5.0
merchant.wechat_pay_less_than_5_count += 1
end
elsif payment_type.start_with?(Alipay)
merchant.alipay.count += 1
merchant.alipay.settlement_amount += row[20].to_f
merchant.alipay.service_charge += row[18].to_f
else
merchant.qqpay.count += 1
merchant.qqpay.settlement_amount += row[20].to_f
merchant.qqpay.service_charge += row[18].to_f
end
end
CSV.open("LanDaResults.csv", "wb") do |csv|
csv << ["", "微信支付", "", "", "支付宝支付", "", "", "QQ钱包", "", "", ""]
csv << ["店铺名称", "交易笔数", "结算金额", "手续费", "交易笔数", "结算金额", "手续费", "交易笔数", "结算金额", "手续费", "交易金额小于5"]
Result.each { |merchant_name, merchant|
csv << [merchant.merchant_name, merchant.wechat.count.to_s, ("%0.2f" % merchant.wechat.settlement_amount).to_s, ("%0.2f" % merchant.wechat.service_charge).to_s,
merchant.alipay.count.to_s, ("%0.2f" % merchant.alipay.settlement_amount).to_s, ("%0.2f" % merchant.alipay.service_charge).to_s,
merchant.qqpay.count.to_s, ("%0.2f" % merchant.qqpay.settlement_amount).to_s, ("%0.2f" % merchant.qqpay.service_charge).to_s,
merchant.wechat_pay_less_than_5_count.to_s]
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment