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的,但是還是習慣當做一種腳本來寫。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章