MENU

置顶
我的感想2-3月份

最近两个月以来,一直是熬夜状态,睡不好觉。

Read More

python秒存数据excel,mysql

import json
import pymysql
import datetime
import json
import os
from openpyxl import Workbook
import time
<!--more-->
def count_time(func):
    def int_time(*args, **kwargs):
        start_time = datetime.datetime.now()  # 程序开始时间
        func()
        over_time = datetime.datetime.now()   # 程序结束时间
        total_time = (over_time-start_time).total_seconds()
        print('程序共计%s秒' % total_time)
    return int_time

@count_time
def to_mysql():
    conn = pymysql.connect(host='localhost',port=3306,user='root',passwd='root',db="jhshop")
    #创建游标
    cursor = conn.cursor()
    with open('jhshop1.json','r',encoding='utf-8')as f:
        list1 = (i for i in f.readlines())
        count =0
        for k in list1:
            k1 = json.loads(k)
            price1 = k1["price"].replace("¥","")
            name1 = k1["name"]
            shop_name1 = k1["shop_name"]
            zxl1 = int(k1["zxl"])
            pingjia1 = int(k1["pingjia"])
            cursor.execute("insert into jjshop (name, price, shopname, zxl, pingjia) values (%s, %s, %s, %s, %s)",
                       (name1,price1,shop_name1,zxl1,pingjia1))
            # cursor.execute("INSERT INTO jjshop (name,price,shopname,zxl,pingjia) VALUES (%s,%s,%s.%s.%s)",
            #                (name1,price1,shop_name1,zxl1,pingjia1))
            conn.commit()
            count +=1
            print("执行成功{}".format(count))

    conn.close()
    cursor.close()







wb = Workbook()
ws = wb.active

cols = []

def json2excel(jsfile, excfile):
    # 读取json数据
    a = 1
    if os.path.exists(jsfile):
        # 先用key值写表头
        with open(jsfile, 'r', encoding='utf8') as fp:
            # 先用key值写表头
            line = fp.readline()
            if not line:
                print("没有内容")
            else:
                # 每一行转换成字典类型
                jsdata = json.loads(line)
                # 用key值做标题
                for k in jsdata.keys():
                    if k not in cols:
                        cols.append(k)
                ws.append(cols)  # 标题
        # 写值
        with open(jsfile, 'r', encoding='utf8') as fp:
            # 循环写值
            while True:
                print('正在写入的行数%s:' % a)
                line = fp.readline()
                if not line:
                    break
                # 转换为python对象
                jsdata = json.loads(line)
                rowdata = []
                for col in cols:
                    # 获取每一行key值对应的value值
                    rowdata.append(jsdata.get(col))
                a += 1
                ws.append(rowdata)  # 写行
        # ws.append(cols) # 标题
    print('保存中')
    wb.save(excfile)  # 保存


if __name__ == '__main__':
    s_time = time.time()
    jsfile = "jhshop.json"
    excfile = "jhshop.xlsx"
    json2excel(jsfile, excfile)
    e_time = time.time()
    print("耗时%s秒"%(e_time-s_time))

Read More

python中自动化格式json数据

class JsonFormatter:
    def __init__(self, intend=4, name="", encoding="utf-8"):
        '''
        intend: 缩进空格数
        name: 文件名
        encoding: 文件编码
        '''
        self.name = name
        self.intend = intend
        self.encoding = encoding
        self.stack = []
        self.obj = None
        self.source = self.get_source(name, self.encoding)
        self.prepare()
<!--more-->
    @staticmethod
    def json_str(s):
        '''
        给字符串套上双引号
        '''
        return '"' + s + '"'

    @staticmethod
    def get_source(name, encoding="utf-8"):
        with open(name, 'r', encoding=encoding) as f:
            # 当不给split函数传递任何参数时,分隔符sep会采用任意形式的空白字符:空格、tab、换行、回车以及换页符
            return ''.join(f.read().split())

    def prepare(self):
        try:
            # python对象和json格式还是略有不同
            self.source = self.source.replace("null", "None").replace("true", "True").replace("false", "False")
            self.obj = eval(self.source)
        except:
            # json string 一定满足python dict和list的组合
            raise Exception('Invalid json string!')

    def line_intend(self, level=0):
        return '\n' + ' ' * self.intend * level

    def parse_dict(self,obj=None,intend_level=0):
        if intend_level == 0:
            # 这个判断是为了防止文件开头出现空行
            self.stack.append('{')
        else:
            self.stack.append(self.line_intend(intend_level)+'{')
        intend_level += 1
        i = 0
        for key, value in obj.items():
            key = self.json_str(str(key))
            self.stack.append(self.line_intend(intend_level)+key+':')
            self.parse(value, intend_level)
            if i != len(obj.items())-1:
                # 这个处理是为了防止最后一对kv后面还有个逗号,这样会造成json.load()函数无法读取
                self.stack.append(',')
            i += 1
        self.stack.append(self.line_intend(intend_level-1)+'}')

    def parse_list(self, obj=None, intend_level=0):
        if intend_level == 0:
            self.stack.append('[')
        else:
            self.stack.append(self.line_intend(intend_level)+'[')
        intend_level += 1
        for i, item in zip(range(0, len(obj)), obj):
            self.parse(item, intend_level)
            if i != len(obj)-1:
                self.stack.append(',')
        self.stack.append(self.line_intend(intend_level-1)+']')

    def parse(self, obj, intend_level=0):
        if obj is None:
            self.stack.append('null')
        elif obj is True:
            self.stack.append('true')
        elif obj is False:
            self.stack.append('false')
        elif isinstance(obj, (int, float)):
            self.stack.append(str(obj))
        elif isinstance(obj, str):
            self.stack.append(self.json_str(obj))
        elif isinstance(obj, (list, tuple)):
            self.parse_list(obj, intend_level)
        elif isinstance(obj, dict):
            self.parse_dict(obj, intend_level)
        else:
            raise Exception('Invalid json type %s!' % obj)

    def render(self):
        self.parse(self.obj, 0)
        res_file = self.name
        res = ''.join(self.stack)
        with open(res_file, 'w', encoding=self.encoding) as f:
            f.write(res)

if __name__ == "__main__":
    jf = JsonFormatter(name="nba.json")
    jf.render()

Read More

代码镇楼

代码镇楼


//                           o8888888o
//                           88" . "88
//                           (| -_- |)
//                            O\ = /O
//                        ____/`---'\____
//                      .   ' \\| |// `.
//                       / \\||| : |||// \
//                     / _||||| -:- |||||- \
//                       | | \\\ - /// | |
//                     | \_| ''\---/'' | |
//                      \ .-\__ `-` ___/-. /
//                   ___`. .' /--.--\ `. . __
//                ."" '< `.___\_<|>_/___.' >'"".
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |
//                 \ \ `-. \_ __\ /__ _/ .-` / /
//         ======`-.____`-.___\_____/___.-`____.-'======
//
<!--more-->                            `=---='
//
//         .............................................
//                  佛祖镇楼                  BUG辟易
//          佛曰:
//                  写字楼里写字间,写字间里程序员;
//                  程序人员写程序,又拿程序换酒钱。
//                  酒醒只在网上坐,酒醉还来网下眠;
//                  酒醉酒醒日复日,网上网下年复年。
//                  但愿老死电脑间,不愿鞠躬老板前;
//                  奔驰宝马贵者趣,公交自行程序员。
//                  别人笑我忒疯癫,我笑自己命太贱;
//                  不见满街漂亮妹,哪个归得程序员?
/*
*  ┏┓   ┏┓
*┏┛┻━━━┛┻┓
*┃       ┃  
*┃   ━   ┃
*┃ ┳┛ ┗┳ ┃
*┃       ┃
*┃   ┻   ┃
*┃       ┃
*┗━┓   ┏━┛
*  ┃   ┃神兽保佑
*  ┃   ┃代码无BUG!
*  ┃   ┗━━━┓
*  ┃       ┣┓
*  ┃       ┏┛
*  ┗┓┓┏━┳┓┏┛
*   ┃┫┫ ┃┫┫
*   ┗┻┛ ┗┻┛ 
*   
*/
<!--
        ´´´´´´´´██´´´´´´´
        ´´´´´´´████´´´´´´
        ´´´´´████████´´´´
        ´´`´███▒▒▒▒███´´´´´
        ´´´███▒●▒▒●▒██´´´
        ´´´███▒▒▒▒▒▒██´´´´´
        ´´´███▒▒▒▒██´                      项目:vue-user-center
        ´´██████▒▒███´´´´´                 语言: ES6-babel
        ´██████▒▒▒▒███´´                   框架: vue+vue-router+vuex+iview+axios
        ██████▒▒▒▒▒▒███´´´´                构建工具: webpack
        ´´▓▓▓▓▓▓▓▓▓▓▓▓▓▒´´                 版本控制: git-github
        ´´▒▒▒▒▓▓▓▓▓▓▓▓▓▒´´´´´              css预处理: less
        ´.▒▒▒´´▓▓▓▓▓▓▓▓▒´´´´´              代码风格:eslint-standard
        ´.▒▒´´´´▓▓▓▓▓▓▓▒                   编辑器: phpstorm
        ..▒▒.´´´´▓▓▓▓▓▓▓▒                  数据库:  mysql
        ´▒▒▒▒▒▒▒▒▒▒▒▒                      服务器端脚本: php go
        ´´´´´´´´´███████´´´´´              author: codeRabbit
        ´´´´´´´´████████´´´´´´´
        ´´´´´´´█████████´´´´´´
        ´´´´´´██████████´´´´             大部分人都在关注你飞的高不高,却没人在乎你飞的累不累,这就是现实!
        ´´´´´´██████████´´´                     我从不相信梦想,我,只,相,信,自,己!
        ´´´´´´´█████████´´
        ´´´´´´´█████████´´´
        ´´´´´´´´████████´´´´´
        ________▒▒▒▒▒
        _________▒▒▒▒
        _________▒▒▒▒
        ________▒▒_▒▒
        _______▒▒__▒▒
        _____ ▒▒___▒▒
        _____▒▒___▒▒
        ____▒▒____▒▒
        ___▒▒_____▒▒
        ███____ ▒▒
        ████____███
        █ _███_ _█_███
——————————————————————————女神保佑,代码无bug——————————————————————
-->
#
#    ┏┓   ┏┓
#   ┏┛┻━━━┛┻┓
#   ┃        ┃
#   ┃   ━    ┃
#   ┃ ┳┛ ┗┳ ┃
#   ┃        ┃
#   ┃   ┻    ┃
#   ┃        ┃
#   ┗━┓   ┏━┛Codes are far away from bugs with the animal protecting
#     ┃   ┃    神兽保佑,代码无bug
#     ┃   ┃
#     ┃   ┗━━━┓
#     ┃      ┣┓
#     ┃     ┏┛
#     ┗┓┓┏━┳┓┏┛
#      ┃┫┫ ┃┫┫
#      ┗┻┛ ┗┻┛
#
#    ┏┓   ┏┓
#   ┏┛┻━━━┛┻┓
#   ┃        ┃  
#   ┃   ━    ┃
#   ┃ >   <┃
#   ┃        ┃
#   ┃ . ⌒ ..┃
#   ┃        ┃
#   ┗━┓   ┏━┛
#     ┃   ┃ Codes are far away from bugs with the animal protecting       
#     ┃   ┃ 神兽保佑,代码无bug
#     ┃   ┃           
#     ┃   ┃       
#     ┃   ┃
#     ┃   ┃           
#     ┃   ┗━━━┓
#     ┃       ┣┓
#     ┃       ┏┛
#     ┗┓┓┏━┳┓┏┛
#      ┃┫┫ ┃┫┫
#      ┗┻┛ ┗┻┛
#        ┏┓   ┏┓+ +
#   ┏┛┻━━━┛┻┓ + +
#   ┃       ┃  
#   ┃   ━   ┃ ++ + + +
#   ████━████ ┃+
#   ┃       ┃ +
#   ┃   ┻   ┃
#   ┃       ┃ + +
#   ┗━┓   ┏━┛
#     ┃   ┃           
#     ┃   ┃ + + + +
#     ┃   ┃    Codes are far away from bugs with the animal protecting   
#     ┃   ┃ +     神兽保佑,代码无bug  
#     ┃   ┃
#     ┃   ┃  +         
#     ┃    ┗━━━┓ + +
#     ┃        ┣┓
#     ┃        ┏┛
#     ┗┓┓┏━┳┓┏┛ + + + +
#      ┃┫┫ ┃┫┫
#      ┗┻┛ ┗┻┛+ + + +

Read More

搬家QAQ

从4人宿舍搬了出来,不是相处的不愉快,反而我跟其他人相处很愉快的。

我只是希望自己有个干净的小窝,每天都能充满能量,充实的生活着。

Read More