September 30, 2014
 
 
RSSRSS feed

Python Squeezes the Web - page 4

Introduction

  • October 23, 1999
  • By Stephen Pitts

While regular expressions form a key part of this program, they didn't account for the fivefold performance increase I experienced when porting this program from C++ to Python! The secret lies in the statement: if this_player.PlayerId not in player_id_list: continue. Before, with C++, I was stuck between tough choices: suffer the performance penalty of hitting the database more times than needed (by issuing an UPDATE statement for each row) or taking the time to implement a binary search algorithm. Being pressed for time, I chose the former and immediately regretted it. Luckily, Python came along and saved the day, yet again, with its rich, powerful data types built into the language itself.

Also, as another example of Python's flexibility, it can be used as the embedded scripting language for VIM. While writing this article, I grew tired of manually replacing > with >, so I composed the following function and put it in ~/vim-htmlify.py:

 
# a little macro for VIM that helps when composing HTML documents
import vim, string, htmlentitydefs
htmlequivs = {}
# swap built-in table, we want a dictionary indexed by
# characters that can't be used.
for key, value in htmlentitydefs.entitydefs.items():
        if key != "amp":
                htmlequivs[value] = key
def htmlify():
        for i in range(0, len(vim.current.range)):
                cLine = vim.current.range[i]
                                cLine = string.replace(cLine, "&", "&")
                for badchar in htmlequivs.keys():
                        cLine = string.replace(cLine, badchar, "&" + h
tmlequivs[badchar] + ";")
                vim.current.range[i] = cLine
        print len(vim.current.range), "line(s) HTMLified"


and put this in ~/.vimrc:


pyfile ~/vim-htmlify.py
map h :py htmlify()

With the touch of "h", I could convert Foo Bar into &amplt;b&ampgt;Foo Bar&amplt;b&ampg. This is yet another example of the power and ubiquity of Python!

 

Sitemap | Contact Us