首页 > 代码库 > python小练习

python小练习

python版本使用的是2.7

工作中正好将正在学习的python用上,如果使用java写的话太麻烦,代码行数远比python要多。

第一个例子是根据id的列表生成insert语句插入到某个简单的表,因为需要做联合查询,所以新建一张一个字段的表,id安行存储在文件中:

import os
curdir = os.getcwd()
count = 0
sql = 'delete from test_userid;\ncommit;\n'
destFile = os.path.join(curdir,'mobile.sql')
with open(os.path.join(curdir,'mobile.dat')) as f:
    for userid in f.readlines():
        if userid == '\n':
            continue
        userid = userid.strip('\n')
        sql += 'insert into test_userid values(\'' + userid + '\');\n'
        count+=1
        if count % 500 == 0:
            sql+='commit;\n'
with open(destFile,'w') as fw:
    fw.writelines(sql)
    fw.close()
print 'convert success and the count is : %d' %count 
        
每500行commit一次,涉及到了简单文件读写操作。

第二个例子是需要提取eclipse生成的.classpath文件中的classpath路径,用到了python的正则表达式:

import re
with open("D:\workspace\Client\.classpath") as f:
    cpStr = ''
    for line in f.readlines():
        p = re.compile(r'.*kind="lib".*path="(.*?)"')
        result = p.findall(line)
        if len(result) > 0:
            cpStr += p.findall(line)[0]
            cpStr += ";"
    print cpStr

一个典型的.classpath文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<classpath>
	<classpathentry kind="src" path="src/main/java"/>
	<classpathentry kind="src" path="src/main/resources"/>
	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
	<classpathentry kind="lib" path="lib/thirdparty/dsf/protostuff-runtime-1.0.7.fixed.3300.jar"/>
	<classpathentry kind="lib" path="lib/thirdparty/dsf/xz-1.4.jar"/>
	<classpathentry kind="lib" path="lib/thirdparty/dsf/zookeeper-3.4.5.jar"/>
	<classpathentry kind="lib" path="lib/commonservice.api-V300R003C20B301-SNAPSHOT.jar"/>
	<classpathentry kind="output" path="classes"/>
</classpath>

需要提取的是path="" 双引号中的值。

第三个小例子涉及到了GUI,说是界面其实是python中最简单的界面编程,使用的是TK,python自带的界面编程库:

# -*- coding: utf-8 -*- 
#简单的日志排版工具,方便查看日志信息,定位问题
from Tkinter import *
#创建主窗口
win = Tk()
#创建输入文本框
textArea = Text(win)
textArea.pack()

#创建frame
frame = Frame(win)
frame.pack()

#指定button的父容器为frame
button = Button(frame,text='fomat')
button.pack(side=LEFT)

clearButton = Button(frame,text='clear')
clearButton.pack(side=RIGHT)

#创建结果文本框
textResult = Text(win)
textResult.pack(side=LEFT)

#创建滚动条
s = Scrollbar(win)
s.pack(side = RIGHT,fill = Y)
#绑定textResult和滚动条
textResult['yscrollcommand'] = s.set
s['command'] = textResult.yview
def formatText(e):
    count = 0
    flag = 0
    #获取文本
    content = textArea.get(0.0,END)
    for i in range(len(content)):
        text = content[i]
        if text == ' ':
            continue
        if text == '[' or text == '{':
            flag = 1
            printBalnk(count, text)
            count+=1
        elif text == ']' or text == '}':
            count-=1
            printBalnk(count, text,0)
        else:
            printCommon(count,text,flag)
            if text == ',':
                flag = 1
            else:
                flag = 0
def printBalnk(count,text,flag=1):
    textResult.insert(CURRENT,'\n')
    for i in range(count):
        textResult.insert(CURRENT,'    ')
    if flag == 1:
        textResult.insert(CURRENT,text + '\n')
    else:
        textResult.insert(CURRENT,text)
def printCommon(count,text,flag):
    if flag == 1:
        for i in range(count):
            textResult.insert(CURRENT, '    ')
    textResult.insert(CURRENT,text)
    if text == ',':
        textResult.insert(CURRENT,'\n')
def selectText(e):
    textResult.tag_add('select_all','1.0',END)
    textResult.tag_config('select_all', foreground='red')
    return 'break'
def clearSelectAll(e):
    textResult.tag_config('select_all', foreground='black')
def clipboard(e):
    content = textResult.get('1.0',END)
    textResult.clipboard_clear()
    textResult.clipboard_append(content)
def clearText(e):
    textArea.delete(0.0, END)
    textResult.delete(0.0, END)
button.bind('<Button-1>', formatText)
clearButton.bind('<Button-1>', clearText)
textResult.bind('<Control-Key-a>', selectText)
textResult.bind('<ButtonRelease-1>',clearSelectAll)
textResult.bind('<Control-Key-c>',clipboard)
win.mainloop()

程序中打印的日志信息并没有排版,定位问题查看起来非常不方便,因此做了上面的排版小工具,实现的原理很简答,就是换行+特定空格打印日志,原始的日志信息类似下面:

20dd5-0dd-dd9 00:47:dd2ddd62|infosmdqwadion|sdsqudssad|q|disdsqwadPdqwymdsnad|OadHdssS|qwGW:dd92ddd68ddd2d223|000000dd0000dd50dddd90047dd2027dd000||||||| 
qwonaddsnad= [sdsqObj = DisdsqwadPdqwymdsnadsdsq [qwomdhudqwwdsidjdqwgudqwsdqwgwdpdqwymdsnaddsdsqudssaddDisdsqwadPdqwymdsnadsdsq@7224f60qw, qwsdsdqwaddsPdqwymdsnadInfo=qwsdsdqwaddsPdqwymdsnadInfo [qwomdhudqwwdsidjdqwgudqwsdqwgwdsqwhdsmdqwdqwsdsdqwaddsPdqwymdsnadInfo@5895qw85f, qwdqwnqwdslUsL=null, qwussdsnqwy=0, dsxaddsnsionInfo=[NdqwmdsdPdqwsdqwmdsaddss [kdsy=isGudqwsdqwnaddsds, vdqwluds=0], NdqwmdsdPdqwsdqwmdsaddss [kdsy=qwlidsnadID, vdqwluds=null], NdqwmdsdPdqwsdqwmdsaddss [kdsy=isGudqwsdqwnaddsds, vdqwluds=0]] 

排完后:

20dd5-0dd-dd900:47:dd2ddd62|infosmdqwadion|sdsqudssad|q|disdsqwadPdqwymdsnad|OadHdssS|qwGW:dd92ddd68ddd2d223|000000dd0000dd50dddd90047dd2027dd000|||||||
qwonaddsnad=
[
    sdsqObj=DisdsqwadPdqwymdsnadsdsq
    [
        qwomdhudqwwdsidjdqwgudqwsdqwgwdpdqwymdsnaddsdsqudssaddDisdsqwadPdqwymdsnadsdsq@7224f60qw,
        qwsdsdqwaddsPdqwymdsnadInfo=qwsdsdqwaddsPdqwymdsnadInfo
        [
            qwomdhudqwwdsidjdqwgudqwsdqwgwdsqwhdsmdqwdqwsdsdqwaddsPdqwymdsnadInfo@5895qw85f,
            qwdqwnqwdslUsL=null,
            qwussdsnqwy=0,
            dsxaddsnsionInfo=
            [
                NdqwmdsdPdqwsdqwmdsaddss
                [
                    kdsy=isGudqwsdqwnaddsds,
                    vdqwluds=0
                ],
                NdqwmdsdPdqwsdqwmdsaddss
                [
                    kdsy=qwlidsnadID,
                    vdqwluds=null
                ],
                NdqwmdsdPdqwsdqwmdsaddss
                [
                    kdsy=isGudqwsdqwnaddsds,
                    vdqwluds=0
                ]
            ]

一直在使用java编程,偶尔用用shell,python既有java强大的功能又有shell的简单,由于刚学python,虽说它是可以OO的,但是还是习惯当做一种脚本来写。

python小练习