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)
格式需要注意,第一话,就这样吧
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章