Python
2016-03-02 17:38
211 查看
python 片段:
1.excel操作
注意
2.redis
1.excel操作
#!/usr/bin/python # -*- coding: cp936 -*- ''' get relation_tag from excel ''' import xlrd import MySQLdb import sys reload(sys) sys.setdefaultencoding( "utf-8" ) try: #写库 conn = MySQLdb.connect(host="localhost",port=3307,user="user",passwd="pwd",db="db",charset="utf8") cursor = conn.cursor() isql = "insert into t_relation_tags(tag_id,rel_tag_id) (select id,-1 from t_tags where tag_name = %s)" usql = "update t_relation_tags set rel_tag_id = (select ifnull(id,-1) from t_tags where tag_name = %s) where rel_tag_id = -1" data = xlrd.open_workbook('.\20160229.xlsx') table = data.sheets()[0] nrows = table.nrows for i in range(nrows): tagName = (table.row_values(i)[0]) #参数2使用元组 cursor.execute(isql,(tagName,)) #conn.commit() relTagName = (table.row_values(i)[1]) print usql %(relTagName) cursor.execute(usql,(relTagName,)) conn.commit() conn.close() except MySQLdb.Error,e: conn.close() print "Mysql Error %d: %s" % (e.args[0], e.args[1])
注意
cursor.execute(usql,(relTagName,))python1.2.5第二个参数必须使用元组形式
2.redis
#!/usr/bin/python ''' sync tags at first time ''' import sys reload(sys) sys.setdefaultencoding('utf-8') raw_out = sys.stdout flog=open('tag.log','aw') sys.stdout=flog import time def log(*s): print time.strftime('%Y-%m-%d %H:%M:%S'), for ss in s: print ss, print flog.flush() import redis import MySQLdb #redis写库 HOST_NAME='localhost' PORT=6379 #读库 conn = MySQLdb.connect(host="localhost",port=3307,user="user",passwd="pwd",db="db",charset="utf8") cursor = conn.cursor() pool = redis.ConnectionPool(host=HOST_NAME,port=PORT,db=0) r = redis.Redis(connection_pool=pool) def tag_catch(): sql = "select t.id,t.tag_name,count(tag_id) from t_tags t left join t_app_tags t2 on t.id = t2.tag_id group by t.id"; #print "sql"+sql count = cursor.execute(sql) return cursor.fetchall() def cache_tags(tags): for tag in tags: dic = {"id":str(tag[0]),"tag":str(tag[1]),"count":str(tag[2])} r.hmset("appinfo:tag:"+str(tag[0]),dic); if __name__ == "__main__": stime = time.time() tags = tag_catch() cache_tags(tags) log("cache model infos takes:"+ str(time.time()-stime));
相关文章推荐
- Python学习记录(三)
- 一次Python爬虫的修改,抓取淘宝MM照片
- Python多线程学习
- Python学习记录(二)
- 数据科学界华山论剑:R与Python巅峰对决
- 老李分享:Python开发性能测试脚本
- Python-----sorted
- Python-----filter
- python学习
- Python学习记录(一)
- Python-----map/reduce
- Python 变量类型
- Python学习十一——theano库符号求导示例代码
- 贝叶斯2-朴素贝叶斯的python实现
- 自学Python之 基础语法
- 统计某招聘网岗位职责要求关键字权重
- Python-代码对象
- 机器学习一小步:Kaggle上的练习Titanic: Machine Learning from Disaster(二)
- Python使用设计模式中的责任链模式与迭代器模式的示例
- python字符串操作和string模块代码分析