What's wrong with this subroutine?
A.Newby
deathtospam43423 at altavista.com
Mon Feb 25 20:45:58 EST 2002
First, here's what I'm trying to do ......
I'm working on a html, cgi based chat script. It's working pretty well so
far.
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. For e.g, to post a
pic of a walrus, you would simply type ....
http://www.pbs.org/kratts/world/oceans/walrus/images/walrus.jpg
... and the script would take that, and before writing it to the chat log
it would convert it to ...
<img src = http://www.pbs.org/kratts/world/oceans/walrus/images/walrus.jpg>
... or to post a link, the user would simply type ...
http://www.goodvibes.com/
... and the script would convert it to ....
<a href = "http://www.goodvibes.com/>Link!</a>
Here's the subroutine I'm using to try and do this.... it is called from a
function named "infilter" which filters the posts before writing them to
the chat log ...
def search4URL(string):
#the following bits are used to alter the post when it finds the URL
beginpic = " <img src ="
endpic = ">"
beginlink = " <a href ="
endlink = " target = blank>Link</a>"
URLStarts = string.find(' http:') #space is so when the function
#repeats, it won't convert the same
#block of text again
URLEnds = string.find(' ', URLStarts+1, len(string))
plaything = string[URLStarts: URLEnds]
if plaything[-4:] == ".jpg" or plaything[-4:] == ".gif": #if the URL is
#a pic
nstring = string.replace(plaything,beginpic+plaything[1:]+ endpic)
elif not plaything[-4:] == ".jpg" or plaything[-4:] == ".gif":
#for some reason, "else:" return a "ValueError: empty pattern string"
nstring=string.replace(plaything,beginlink+plaything[1:]+ endlink)
return nstring
...... The problem (aside from the fact that someone clever could probably
neaten it up), is that it only works ONCE per post. That means, that if a
chatter tries to post two pics, or a pic and a link, the URLs just come out
as plain text. Any more than once and get a "ValueError: empty pattern
string".
I have tried fixing the routine in "infilter" so it repeats the function as
many times as it finds the substring " http:". I have tried doing this ...
x = searchstring.count(' http:')
for c in range(0, x):
searchstring = search4URL(searchstring)
... And I've also tried using a while loop instead. But I keep getting the
dread ValueError. What am I missing here?
--
cdewin at dingoblue.net.au
More information about the Python-list
mailing list