基於Python的網頁文檔處理指令碼實現,

來源:互聯網
上載者:User

基於Python的網頁文檔處理指令碼實現,

  嵌入式web伺服器不同於傳統伺服器,web需要轉換成數組格式儲存在flash中,才方便lwip網路介面的調用,最近因為業務需求,需要頻繁修改網頁,每次的壓縮和轉換就是個很繁瑣的過程,因此我就有了利用所掌握的知識,利用python編寫個能夠批量處理網頁檔案,壓縮並轉換成數組的指令碼。

  指令碼運行背景(後續版本相容):

      Python 3.5.1(下載、安裝、配置請參考網上教程)

      node.js v4.4.7, 安裝uglifyjs管理組件,支援js檔案非文本壓縮

      uglifyjs 用來壓縮JS檔案的引擎,具體安裝可參考http://www.zhangxinxu.com/wordpress/2013/01/uglifyjs-compress-js/

      具體實現代碼如下:

#/usr/bin/pythonimport osimport binasciiimport shutil from functools import partialdef FileReduce(inpath, outpath):        infp = open(inpath, "r", encoding="utf-8")        outfp = open(outpath, "w", encoding="utf-8")        print(outpath+" 壓縮成功")        for li in infp.readlines():            if li.split():                li = li.replace('\n', '').replace('\t', '');                li = ' '.join(li.split())                outfp.writelines(li)        infp.close()        outfp.close()#shell命令列調用(用ugllifyjs2來壓縮js檔案)def ShellReduce(inpath, outpath):    Command = "uglifyjs "+inpath+" -m -o "+outpath    print(Command)    os.system(Command)#將檔案以二進位讀取, 並轉化成數組儲存def filehex(inpath, outpath):    i = 0    count = 0    a = ''    inf = open(inpath, 'rb');    outf = open(outpath, 'w')    records = iter(partial(inf.read,1), b'')    print(outpath + " 轉換成數組成功")    for r in records:        r_int = int.from_bytes(r, byteorder='big')          a +=  hex(r_int) + ', '        i += 1        count += 1        if i == 16:                         a += '\n'            i = 0    a = "const static char " + outpath.split('.')[0].split('/')[-1] + "["+ str(count) +"]={\n" + a + "\n}\n\n"     outf.write(a)    inf.close()    outf.close()#建立一個新檔案夾def mkdir(path):    path=path.strip()    isExists=os.path.exists(path)     #判斷檔案夾是否存在,不存在則建立    if not isExists:        print(path+' 建立成功')        os.makedirs(path)    else:        pass    return path#刪除一個檔案夾(包含內部所有檔案)def deldir(path):    path = path.strip()    isExists=os.path.exists(path)     #判斷檔案夾是否存在,存在則刪除    if isExists:        print(path + "刪除成功")        shutil.rmtree(path)    else:        passdef WebProcess(path):        #原網頁 ..\basic\          #壓縮網頁 ..\reduce\        #編譯完成.c網頁 ..\programe        BasicPath = path + "\\basic"        ProgramPath = path + "\\program"        ReducePath = path + "\\reduce"                #刪除原檔案夾,再建立新檔案夾        deldir(ProgramPath)        deldir(ReducePath)        mkdir(ProgramPath)        for root, dirs, files in os.walk(BasicPath):                for item in files:                        ext = item.split('.')                        InFilePath = root + "/" + item                        OutReducePath = mkdir(root.replace("basic", "reduce")) + "/" + item                        OutProgramPath = ProgramPath + "/" + item.replace('.', '_') + '.c'                                                #根據尾碼不同進行相應處理                        #html/css 去除'\n','\t', 空白字元保留1個                        #js 調用uglifyjs2進行壓縮                        #gif jpg ico 直接拷貝                         #其它 直接拷貝                        #除其它外,剩餘檔案同時轉化成16進位數組, 儲存為.c檔案                        if ext[-1] in ["html", "css"]:                            FileReduce(InFilePath, OutReducePath)                            filehex(OutReducePath, OutProgramPath)                        elif ext[-1] in ["js"]:                            ShellReduce(InFilePath, OutReducePath)                            filehex(OutReducePath, OutProgramPath)                        elif ext[-1] in ["gif", "jpg", "ico"]:                            shutil.copy(InFilePath, OutReducePath)                            filehex(OutReducePath, OutProgramPath)                        else:                            shutil.copy(InFilePath, OutReducePath)#獲得當前路徑path = os.path.split(os.path.realpath(__file__))[0];WebProcess(path)

上述實現的原理主要包含:

1.遍曆待處理檔案夾(路徑為..\basic,需要使用者建立,並將處理檔案複製到其中,並將指令碼放置到該檔案夾上一層)--WebProcess

2.建立壓縮分頁檔夾(..\reduce, 用於儲存壓縮後檔案), 由指令碼完成,處理動作:

 html, css: 刪除文本中的多餘空格,分行符號

   js:調用uglifyjs進行壓縮處理

   gif, jpg, ico和其它: 直接進行複製處理

3.建立處理分頁檔夾(..\program, 用於儲存壓縮後檔案), 由指令碼完成,處理動作:

 以二進位模式讀取檔案,並轉換成16進位字串寫入到該檔案夾中

在檔案夾下(shift+滑鼠右鍵)啟用windows命令列,並輸入python web.py, 就可以通過迴圈重複這三個過程就可以完成所有檔案的處理。

特別注意:所有處理的檔案需要以utf-8格式儲存,否則讀取時會報"gbk"讀取錯誤。

實現效果如

html檔案:

轉換數組:

樣本可參考:

http://files.cnblogs.com/files/zc110747/webreduce.7z

另外附送一個小的指令碼,查詢目前的目錄及子檔案夾下選定程式碼數和空行數(算是寫這個指令碼測試時衍生出來的):

#/usr/bin/pythonimport ostotal_count = 0; empty_count = 0;def CountLine(path):        global total_count        global empty_count        tempfile = open(path)        for lines in tempfile:                total_count += 1                if len(lines.strip()) == 0:                       empty_count += 1 def TotalLine(path):        for root, dirs, files in os.walk(path):                for item in files:                        ext = item.split('.')                        ext = ext[-1]                          if(ext in ["cpp", "c", "h", "java", "php"]):                                subpath = root + "/" + item                                CountLine(subpath)path = os.path.split(os.path.realpath(__file__))[0];TotalLine(path)print("Input Path:", path)print("total lines: ",total_count)print("empty lines: ",empty_count)print("code lines: ", (total_count-empty_count))

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.