In [105]:
import json
import urllib
import pandas as pd
import random
import numpy as np
import datetime

cnv2utf8 (網址中文部分需要用URLEncode 轉換成 UTF-8)


In [106]:
def cnv2utf8(mstr):
    #print mstr
    #print urllib.quote(mstr.encode(u"utf8"))
    return urllib.quote(mstr.encode(u"utf8"))

可以看json中文字的程式碼


In [107]:
class MyPrettyPrinter(pprint.PrettyPrinter):
    def format(self, object, context, maxlevels, level):
        if isinstance(object, unicode):
            return (object.encode('utf8'), True, False)
        return pprint.PrettyPrinter.format(self, object, context, maxlevels, level)
def printJson(aObj):
    MyPrettyPrinter().pprint(aObj)

傳入六個變數,回傳一個Json

  • 地點
  • 產品
  • 前幾名資料
  • 跳過多少資料量
  • 交易結束時間
  • 交易開始時間

In [108]:
def cnv2Weekday(mstr):
    yy, mm, dd = mstr.split(".")
    return datetime.datetime(int(yy)+1911, int(mm), int(dd)).weekday()
    
cnv2Weekday('105.06.25')


Out[108]:
5

In [109]:
def getData(location, product, top, skip, EndDate, StartDate):
    
    ##變數宣告
    # url是API的網址
    # ahash是替代的變數值
    url = u"http://m.coa.gov.tw/OpenData/FarmTransData.aspx?$top={top}&$skip={skip}&Market={Market}&Crop={Crop}&EndDate={EndDate}&StartDate={StartDate}"
    ahash={
          u"{top}"      :top,
          u"{skip}"     :skip,
          u"{Market}"   :cnv2utf8(location),
          u"{Crop}"     :cnv2utf8(product),
          u"{EndDate}"  :EndDate,
          u"{StartDate}":StartDate,
    }
    
    ## 這裡再做的就是將ahash內的key用value換掉
    for abc in ahash:
        url=url.replace(abc,ahash[abc])
    #print url

    # 到API抓資料回來
    rsps = urllib.urlopen( url.encode(u"utf8") )
    pd_data = pd.read_json(rsps.read().decode(u"utf8"))
    pd_data['Weekday'] = [ cnv2Weekday(x) for x in pd_data[u'交易日期']]
    return pd_data

In [110]:
getData(u"", u"甘藍", u" ", u"",u"105.06.30",u"102.06.01").to_csv('test.csv', encoding="utf8")

In [111]:
#print "%d-%02d-%02d"%( 105, 8, 1)

In [ ]: