What's wrong with this subroutine?

Tim Legant tim-dated-1015298553.dcf11c at catseye.net
Mon Feb 25 22:22:32 EST 2002


"A.Newby" <deathtospam43423 at altavista.com> writes:

> First, here's what I'm trying to do ......
> 
> I want to get this subroutine so that the user just has to post a url into 
> the chat box to get a post a picture or a link in chat.

Not sure why you're getting a ValueError, but how about this, instead.
The code in the "__name__ == '__main__'" section executes if you run
this as a script from the command line:

$ python URLReplace.py


--- URLReplace.py ---

import os
import re

RE_HTTP = re.compile(r'http://\S+')

def replaceURL(user_text, startidx=0):
    imgtag = '<img src="%s">'
    linktag = '<a href="%s" target="blank">Link</a>'

    matchobj = RE_HTTP.search(user_text, startidx)
    if matchobj:
        url = matchobj.group()
        urltype = os.path.splitext(url)[1]
        if urltype in ('.jpg', '.gif', '.png'):
            tag = imgtag % url
        else:
            tag = linktag % url
        user_text = "%s%s%s" % (user_text[0:matchobj.start()],
                                tag, user_text[matchobj.end():])
        return user_text, matchobj.start() + len(tag)
    return user_text, 0


if __name__ == '__main__':
    text = "http://www.pbs.org/kratts/world/oceans/walrus/images/walrus.jpg\n" \
                  "is a really cool picture.  In fact, the whole site,\n" \
                  "http://www.pbs.org/kratts/world/oceans/ , is pretty awesome.\n"
    print text

    nextidx = 0
    while 1:
        (text, nextidx) = replaceURL(text, nextidx)
        if not nextidx:
            break

    print text

--- end URLReplace.py ---


Tim




More information about the Python-list mailing list