替换Python中的出现

时间:2017-08-09 12:39:13

标签: python python-3.x

我有一个字符串,这个字符串可能包含一些类似的事件:

http://site/image.jpg

通过

替换这种事件的正确方法是什么?

<img src="http://site/image.jpg">

真正重要的是,只替换http开头的.jpg.pnggif结尾的<img> HTML标记

因此,如果在所有文本中都有任何图像的URL链接,则它由HTML标记格式化以显示图像。

2 个答案:

答案 0 :(得分:1)

使用正则表达式非常简单:

import re

string = 'some other text, a URL http://site/image.jpg and other text'

print(re.sub(r'(https?.+?(?:jpg|png|gif))', r'<img src="\1">', string))

# some other text, a URL <img src="http://site/image.jpg"> and other text

(https?.+(?:jpg|png|gif))匹配以httphttps开头,以jpgpnggif结尾的所有内容。

'<img src="\1">'此处\1指的是前一个正则表达式中的第一个(也是唯一一个)捕获组(包含图片网址)。

答案 1 :(得分:1)

这是对您问题的简单回答:

def check_if_image(url, image_extensions):
   if url.startswith("https://") or url.startswith("http://"):
       for extension in image_extensions:
           if(extension in url[-4:]):
               return True
   return False

def main():
   url_seed = ["http://somesite.com/img1.jpg", "https://somesite2.com/img2.gif", 
            "http://somesite3.net/img3.png", "http://noimagesite.com/noimage"]
   image_extensions = [".jpg", ".png", ".gif"]

   final_result=[]
   for site in url_seed:
       if check_if_image(site, image_extensions):
           final_result.append('<img src="%s">' %site)
   print(final_result)

这包括“http”和“https”网站验证,以及用于3个字符图片扩展的代码,例如你问:jpg,gif和png。

希望它有所帮助。 如果您有任何疑问,请随时询问。

编辑:没有注意到您的数据结构中已经没有网址,因此这对您的情况无效