python 實例一則

 經過一天的研究python,寫了一則例子出來,順便經驗總結一下

google招聘的時候有一則就是python程序員,使用後發現作爲腳本的語言雖然有些地方跟傳統的c,java相悖,但是仍然有很強大的功能,各種樣式的庫支持。我自己的理解就是作爲批處理使用
 
先貼個例子:
 
#encoding=utf-8   //用來顯示中文
#this toolkit refresh empty location to real value use google map 
 
import sys
import httplib
import MySQLdb
import json
 
# need reload //同樣是中文所用,但是我自己在windows下使用的時候,遇到reload就會停滯,求解
reload(sys)
sys.setdefaultencoding('utf-8')
 
#connect to database//連接數據庫
db = MySQLdb.connect(host='localhost', user='root', passwd='xxxxxxx', charset='utf8')
 
cur = db.cursor()
cur.execute('use xxx')
cur.execute('select id, name, latitude, longitude from destination where length(name)>0')
cur.scroll(0)
 
#establish http connection to google map
conn = httplib.HTTPConnection("maps.googleapis.com")
base = "/maps/api/geocode/json?address="
 
for row in cur.fetchall():
 
    id = str(row[0]) 
    url = base + str(row[1]) + "&sensor=false"//拼接url
 
    conn.request("GET", url)
    res = conn.getresponse()
    data = res.read()
 
    locations = json.read(data)
    
    if len(locations["results"]) > 0:
        lat = locations["results"][0]["geometry"]["location"]["lat"]
        la = float(lat)
        lng = locations["results"][0]["geometry"]["location"]["lng"]
        ln = float(lng)
        ids = float(id)
        print la
        print ln
        query = "update destination set latitude = %f, longitude = %f where id= %d" %(la,ln,ids)
        print query
    
        cur.execute(query)
        db.commit()
 
cur.close()
 
雖然就是這麼個簡單的例子,最爲初學者我也是學了整一天。
上述這段代碼的功能就是將數據庫表中的數據根據地理位置獲取到經緯度,然後存入。
 
在shell中運行的代碼是python xxx.py
要注意的一點就是數字的帶入:
query = "update destination set latitude = %f, longitude = %f where id= %d" %(la,ln,ids)
格式需要注意,第一話,就這樣吧
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章