python 从文件导入分类
# -*- coding:utf-8 -*-
"""
从文件导入分类 根据行首制表符或空格确定层级关系(4个空格等于一个制表符 同一行制表符和空格不能混用 )
必须是 utf-8编码 -------test.txt-------
鞋子
运动鞋
凉鞋
拖鞋
靴子
体育
羽毛球
单打
双打
游泳
----------------------
""" import redis
import MySQLdb
import json class Category(object): cache = redis.StrictRedis(host='localhost',port = 6379,db=0)
conn = MySQLdb.Connect(host='192.168.1.222', user='root', passwd='', db='gmian',charset='utf8') """
打开文件 读取每一行进行处理
"""
def run(self,category_file):
f = open(category_file,'r')
while True:
#print isinstance(line, unicode) # 检测是否为unicode
#print unicode(line,"utf-8")
line = f.readline()
if line:
self.writeCate(line)
else:
break
f.close() #删除缓存
def __del__(self):
keys = self.__class__.cache.smembers('category_keys')
for key in keys:
self.__class__.cache.delete(key)
self.__class__.cache.delete('category_cateid')
self.__class__.cache.delete('category_keys') #获取自动增长的ID
@classmethod
def getincr(cls):
return int(cls.cache.incr('category_cateid')) + DB_AUTO_INSERT # 把分类添加进按层级分别的列表中
@classmethod
def add(cls,num,catename):
id = cls.getincr()
cls.insert_db(id,num,catename)
cls.cache.sadd('category_keys','category_level_'+str(num))
cls.cache.lpush('category_level_'+str(num),json.dumps([id,catename])) #获取父类
@classmethod
def getparentid(cls,num):
parent = cls.cache.lindex('category_level_'+str(num-1),0)
if not parent:
raise NameError('STOP !! 没找到父类')
parent = json.loads(parent)
return parent[0] @classmethod
def writeCate(cls,line):
num,catename = cls.getLevelNum(line)
cls.add(num,catename) @classmethod
def insert_db(cls,id,num,catename):
if num:
pid = cls.getparentid(num)
else:
pid = 0
cursor = cls.conn.cursor()
cursor.execute("insert into gm_category (cat_id,cat_name,parent_id,style,is_top_style,is_top_show,cat_ico)value(%s,%s,%s,%s,%s,%s,%s)" , (id,catename,pid,'',0,0,''))
cls.conn.commit() # 要么全部是 \t 要么全部是空格 空格4个为一个单位
@staticmethod
def getLevelNum(str):
i = 0
while str[i] == '\t':
i+=1
if i:
return i,str[i:]
while str[i] == ' ':
i+=1
if not i:
return 0,str
return i/4,str[i:] if __name__ == '__main__':
# >$ python category.py 153(DB_AUTO_INSERT) cate1.txt cate2.txt ... import sys
try:
DB_AUTO_INSERT = int(sys.argv[1]) # 已存在的最大ID 否则ID重复 插入失败
files = sys.argv[2:]
if not files:
raise IndexError('input category file')
except IndexError as e:
raise ValueError('---------argv errors-------')
cate = Category()
for file in files:
try:
cate.run(file)
except Exception as e:
print e
print u"【" +file+ u"】导入失败"
python 从文件导入分类的更多相关文章
- 关于python中文件导入的若干问题
__init__文件 同一级目录下直接import导入就可以了,如果是在不同的目录下面被导入文件的文件夹下面必须有__init__.py文件,即使这个文件是空的也可以.当然这个文件也可以初始一些数据 ...
- python将文件导入字典
a={}i=0f = open("filepath","r")for line in f.readlines(): a[i] =line i=i+1 a是字典, ...
- appium+python自动化51-adb文件导入和导出(pull push)
前言 用手机连电脑的时候,有时候需要把手机(模拟器)上的文件导出到电脑上,或者把电脑的图片导入手机里做测试用,我们可以用第三方的软件管理工具直接复制粘贴,也可以直接通过adb命令导入和导出. adb ...
- appium+python自动化-adb文件导入和导出(pull push)
前言 用手机连电脑的时候,有时候需要把手机(模拟器)上的文件导出到电脑上,或者把电脑的图片导入手机里做测试用,我们可以用第三方的软件管理工具直接复制粘贴,也可以直接通过adb命令导入和导出. adb ...
- Python实现鸢尾花数据集分类问题——基于skearn的NaiveBayes
Python实现鸢尾花数据集分类问题——基于skearn的NaiveBayes 代码如下: # !/usr/bin/env python # encoding: utf-8 __author__ = ...
- Python实现鸢尾花数据集分类问题——基于skearn的LogisticRegression
Python实现鸢尾花数据集分类问题——基于skearn的LogisticRegression 一. 逻辑回归 逻辑回归(Logistic Regression)是用于处理因变量为分类变量的回归问题, ...
- Python实现鸢尾花数据集分类问题——基于skearn的SVM
Python实现鸢尾花数据集分类问题——基于skearn的SVM 代码如下: # !/usr/bin/env python # encoding: utf-8 __author__ = 'Xiaoli ...
- Python模块及其导入
一.模块 1.模块的定义: 为了编写可维护的代码,我们把很多函数分组,分别放到不同的文件里,这样,每个文件包含的代码就相对较少, 很多编程语言都采用这种组织代码的方式.在Python中,一个.py文件 ...
- 将.dat文件导入数据库
*最近在搞文本分类,就是把一批文章分成[军事].[娱乐].[政治]等等. 但是这个先需要一些样本进行训练,感觉文本分类和"按图索骥"差不多,训练的文章样本就是"图&quo ...
随机推荐
- android架构
周日没事,简单总结了一下Android开发中使用到的知识,以脑图的形式呈现.
- json学习小记
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...
- (原创)关于SQL Server 2005 的自动远程数据库备份
由于项目需要,需要对目标服务器上的数据库每天进行备份并转移,查阅网上的一些帮助,结合自己的实际需要,写了这篇文章,希望对有同样需求的朋友有所帮助.目标服务器:192.168.1.197,备份服务器:1 ...
- MapReduce的模式、算法和用例
英文原文:<MapReduce Patterns, Algorithms, and Use Cases> https://highlyscalable.wordpress.com/2012 ...
- Cable TV Network-POJ1966图的连通度
Cable TV Network Time Limit: 1000MS Memory Limit: 30000K Total Submissions: 4404 Accepted: 2047 Desc ...
- winform在不同电脑分辨率
private void InitializeComponent() { //设定按字体来缩放控件 this.AutoScaleMode = System.Windows.Forms.AutoScal ...
- nginx简单的rewrite配置
假设当前已存在location /test/,希望配置一个短连接/ts/与之相同,就需要用到rewrite 直接配置到server段 rewrite ^/ts/(.*) /test/$1; 或者放到l ...
- python time模块
time模块 (有效时间1970-2038) (1)本地时间 (2)时间戳 (3)延时 time.localtime([secs]) #struct_time time.time() #timesta ...
- 利用excel拆分数据
要求:将sheet1中的数据按照公司名称拆分到不同的工作表 使用VBA: 1:打开sheet1的查看代码 2:运行 ·········································· ...
- Statement returned more than one row, where no more than one was expected
Statement returned more than one row, where no more than one was expected <resultMap id="Stu ...