【发布时间】:2010-09-22 02:30:56
【问题描述】:
我正在尝试在 python 中的字符串中替换某些内容,但遇到了一些麻烦。这就是我想做的事情。
对于我的帖子中的给定评论:
"here are some great sites that i will do cool things with! https://stackoverflow.com/it's a pig & http://google.com"
我想用 python 来制作这样的字符串:
"here are some great sites that i will do cool things with! <a href="http://stackoverflow.com">http%3A//stackoverflow.com</a> & <a href="http://google.com">http%3A//google.com</a>
这是我目前所拥有的......
import re
import urllib
def getExpandedURL(url)
encoded_url = urllib.quote(url)
return "<a href=\"<a href="+url+"\">"+encoded_url+"</a>"
text = '<text from above>'
url_pattern = re.compile('(http.+?[^ ]+', re.I | re.S | re.M)
url_iterator = url_pattern.finditer(text)
for matched_url in url_iterator:
getExpandedURL(matched_url.groups(1)[0])
但这就是我卡住的地方。我以前在这里看到过这样的事情:Regular Expressions but for Writing in the Match 但肯定有比遍历每场比赛并对其进行位置替换更好的方法。这里的困难在于它不是直接替换,但我需要在替换之前对每场比赛做一些具体的事情。
【问题讨论】: