Use Python to replace an absolute URL with a relative URL

Source: Internet
Author: User
This article describes how to replace an absolute URL with a relative URL in Python. it involves Python string operations and regular expression matching techniques, for more information about how to replace an absolute URL with a relative URL, see the example in this article. Share it with you for your reference. The specific analysis is as follows:

I. problems:

A company project needs to upload images. at first, after uploading images, a colleague combined the current host into an absolute URL (http: // 192.168.1.1: 888/m/getimg? Filename=xxx.jpg) because an interface is provided to the mobile phone terminal at the same time, some bugs may occur in the mobile phone token. after the code is changed, replace the previous uri with the relative URL (/m/getimg? Filename=xxx.jpg). because the image is embedded with the img label and the label is used to enclose the large image, you need to read the database and replace the content.

II. solution:

#!/usr/bin/env python#-*- coding:utf-8 -*-### author : cold night# email  : wh_linux@126.com#import pymongoimport refrom StringIO import StringIOconn = pymongo.Connection()db = conn.testdef replace_url():  regex = re.compile(r'([href¦src])=["¦\']http://.*?(/m/getimg\?.*?)["¦\']')  results = db['test'].find()  db_coll = db['test']  def replace(r):    content = r.get('content')    if not content: return    content = StringIO(content)    content.seek(0)    result = StringIO()    for line in content.readlines():      t = regex.sub(r'\1="\2"', line)      result.write(t)    result.seek(0)    content = result.read()    if content:      r['content'] = content    _id = r.get('_id')    db_coll.update({'_id':_id}, r)  results = [replace(i) for i in results]if __name__=="__main__":replace_url()

I hope this article will help you with Python programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.