Skip to content

Instantly share code, notes, and snippets.

@khiav223577
Last active November 24, 2018 15:51
Show Gist options
  • Save khiav223577/6a3faf5d935e2c7180ea26de35701402 to your computer and use it in GitHub Desktop.
Save khiav223577/6a3faf5d935e2c7180ea26de35701402 to your computer and use it in GitHub Desktop.
2018 台北市長選舉推測票數(依各區票倉的票所數 已送/應送 比例乘上去來推測)
require 'httparty'
class ApiService
include HTTParty
base_uri 'http://vote.2018.nat.gov.tw/mobile/zh_TW/TC'
def load(code)
response = self.class.get("/#{code}.html").parsed_response
response =~ /已送\/應送: (\d+)\/(\d+)/
ratio = $1.to_f / $2.to_f
result = response.scan(/<td>(.*?)<\/td>\n <td>.<\/td>\n <td class=\"numeric\">((?:\d|,)+)<\/td>/).to_a
return result.map do |name, number|
number = number.gsub(',', '').to_i
next [name, [number, number * 1 / ratio.to_f]]
end.to_h
end
end
def get_result
api = ApiService.new
predict_hash = Hash.new(0)
real_hash = Hash.new(0)
{
'松山區' => '63000000100000000',
'信義區' => '63000000200000000',
'大安區' => '63000000300000000',
'中山區' => '63000000400000000',
'中正區' => '63000000500000000',
'大同區' => '63000000600000000',
'萬華區' => '63000000700000000',
'文山區' => '63000000800000000',
'南港區' => '63000000900000000',
'內湖區' => '63000001000000000',
'士林區' => '63000001100000000',
'北投區' => '63000001200000000',
}.each do |key, code|
api.load(code).each do |name, (real_number, predict_number)|
predict_hash[name] += predict_number
real_hash[name] += real_number
end
end
return [predict_hash, real_hash]
end
loop do
predict_hash, real_hash = get_result
puts '---------------------------------------'
p Time.now
predict_sum = predict_hash.values.sum
real_sum = real_hash.values.sum
ratio = real_sum / predict_sum.to_f
puts "\n - 實際票數 (已開 #{(ratio * 100).round(2)}%)"
real_hash.each do |name, number|
puts "%s %8d (%5.2f%%)" % [name, number.round, (number.round * 100.0 / real_sum).round(2)]
end
puts "\n - 預測票數"
predict_hash.each do |name, number|
puts "%s %8d (%5.2f%%)" % [name, number.round, (number.round * 100.0 / predict_sum).round(2)]
end
sleep 30
end
@khiav223577
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment