This article introduces the Python web document processing script instance code embedded web server is different from the traditional server, the web needs to be converted into an array format stored in flash, in order to facilitate the lwip network interface call, recently, due to business needs, we need to modify webpages frequently. Each compression and conversion process is very complicated. Therefore, I have the knowledge to use, use python to compile a script that can process web page files in batches, compress and convert them into arrays.
Script running background (compatible with later versions ):
Python 3.5.1 (for download, installation, and configuration, refer to the online tutorial)
Node. js v4.4.7. install the uglifyjs management package and support non-text compression of js files
Uglifyjs engine used to compress JS files
The specific implementation code is as follows:
#/Usr/bin/pythonimport osimport binasciiimport shutil from functools import partialimport reimport gzip # Create a new folder def mkdir (path): path = path. strip () isExists = OS. path. exists (path) # determine whether a folder exists. if it does not exist, create if not isExists: OS. makedirs (path) print (path + 'created successfully') else: pass return path # delete a folder (including all internal files) def deldir (path): path = path. strip () isExists = OS. path. exists (path) # determine whether a folder exists. if it exists, delete if isExists: shutil. rmtree (Path) print (path + "deleted successfully") else: pass # One-time compressed file def FileReduce (inpath, outpath): infp = open (inpath, "r ", encoding = "UTF-8") outfp = open (outpath, "w", encoding = "UTF-8") for li in infp. readlines (): if li. split (): # Remove redundant \ r \ n li = li. replace ('\ n ',''). replace ('\ t', ''); # Only one li ='' is reserved for spaces ''. join (li. split () outfp. writelines (li) infp. close () outfp. close () print (outpath + "compressed successfully") # shell command line call (use ugllifyjs to compress js File) def ShellReduce (inpath, outpath): Command = "uglifyjs" + inpath + "-m-o" + outpath print (Command) OS. system (Command) # gzip compression module def FileGzip (inpath, outpath): with open (inpath, 'RB') as plain_file: with gzip. open (outpath, 'WB ') as zip_file: zip_file.writelines (plain_file) print (outpath + "gzip-compressed successfully") # read the file in binary format, convert to an array to save def FileHex (inpath, outpath): I = 0 count = 0 a = ''inf = open (inpath, 'RB'); out F = open (outpath, 'w') records = iter (partial (inf. read, 1), B '') for r in records: r_int = int. from_bytes (r, byteorder = 'Big ') a + = strzfill (hex (r_int), 2, 2) + ', 'I + = 1 count + = 1 if I = 16: a + =' \ n' I = 0 a = "const static char" + outpath. split ('. ') [-2]. split ('/') [-1] + "[" + str (count) + "] = {\ n" + a + "\ n} \ n" outf. write (a) inf. close () outf. close () print (outpath + "converted to array succeeded") # fill 0def st in the specified position Rzfill (istr, index, n): return istr [: index] + istr [index:]. zfill (n) # Comment out css /*..... */def unCommentReduce (inpath, outpath): infp = open (inpath, "r", encoding = "UTF-8") outfp = open (outpath, "w ", encoding = "UTF-8") fileByte = infp. read (); replace_reg = re. compile ('/\ * [\ s \ S] *? \ */') FileByte = replace_reg.sub ('', fileByte) fileByte = fileByte. replace ('\ n ',''). replace ('\ t', ''); fileByte = ''. join (fileByte. split () outfp. write (fileByte) infp. close () outfp. close () print (outpath + "to annotate and compress successfully! ") # Main program processing function def WebProcess (path): # Original webpage .. \ basic \ # compressing web pages .. \ reduce \ # gzip secondary compression .. \ gzip # compilation completed. web page C .. \ programe BasicPath = path + "\ basic" ReducePath = path + "\ reduce" GzipPath = path + "\ gzip" ProgramPath = path + "\ program" # Delete original folder, create a new folder named deldir (ProgramPath) deldir (inclucepath) deldir (GzipPath) mkdir (ProgramPath) for root, dirs, files in OS. walk (BasicPath): for item in files: ext = item. split ('. ') InFilePath = root + "/" + item out1_cepath = mkdir (root. replace ("basic", "reduce") + "/" + item OutGzipPath = mkdir (root. replace ("basic", "gzip") + "/" + item + '.gz 'OutProgramPath = ProgramPath + "/" + item. replace ('. ',' _ ') + '. c' # processing based on different suffixes # Remove '\ n',' \ t' in html, and retain 1 space character # Remove css \*...... * \ comment data, '\ n' and' \ t ', at the same time, one space character is retained. # js calls uglifyjs2 for compression. # gif jpg ico for direct copy. # Other direct copies are completed and compressed into a. gz file. # Other files are converted into a hexadecimal array at the same time, save. c file if ext [-1] = 'html': FileReduce (InFilePath, out1_cepath) FileGzip (out1_cepath, OutGzipPath) FileHex (OutGzipPath, OutProgramPath) elif ext [-1] = 'css ': unCommentReduce (InFilePath, out1_cepath) FileGzip (out1_cepath, OutGzipPath) FileHex (OutGzipPath, OutProgramPath) elif ext [-1] = 'js': ShellReduce (InFilePath, out1_cepath) FileGzip (out1_cepath, OutGzipPath) FileHex (OutGzipPath, OutProgramPath) elif ext [-1] in ["gif", "jpg", "ico"]: shutil. copy (InFilePath, out0000cepath) FileGzip (out0000cepath, OutGzipPath) FileHex (OutGzipPath, OutProgramPath) else: shutil. copy (InFilePath, outdomaincepath) # obtain the current path = OS. path. split (OS. path. realpath (_ file _) [0]; WebProcess (path)
The above implementation principles mainly include:
1. traverse the folder to be processed (path: .. \ basic, you need to create, copy the processed file to it, and place the script on the folder) -- WebProcess
2. create a compressed page folder (.. \ reduce, used to store compressed files), which is completed by a script and processed:
Htm: Removes unnecessary spaces and line breaks in text.
Css: Remove unnecessary spaces in the text, line breaks, and comment files /*......*/
Js: call uglifyjs for compression processing
Gif, jpg, ico, and others: directly copy
3. create a gzip file processing folder (.. \ gzip, used to save the files after secondary compression). The script calls the gzip module.
4. create a processing page folder (.. \ program, used to store compressed files), which is completed by the script. the processing action is as follows:
Read the file in binary mode and convert it to a hexadecimal string to write it to the file.
In the folder (shift + right-click), enable windows command line, and input python web. py, you can repeat these three processes to process all the files.
Note: All processed files must be stored in UTF-8 format. Otherwise, an "gbk" read error will be reported during reading.
The implementation result is as follows:
Html file:
In addition, a small script is provided to query the number of lines of the selected code and the number of empty lines in the current directory and subfolders (derived from the script test ):
#/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))
The above describes how to process the script instance code using the Python webpage document. For more information, see other related articles in the first PHP community!