Skip to content

Instantly share code, notes, and snippets.

@movEAX
Last active August 29, 2015 14:20
Show Gist options
  • Save movEAX/7ca78153e5eaf0eafd98 to your computer and use it in GitHub Desktop.
Save movEAX/7ca78153e5eaf0eafd98 to your computer and use it in GitHub Desktop.
Replace short links in text to full links
import requests
import re
DOMAINS = ['bit.ly']
PATTERN = 'https?://{}/\w+'
def expand_short_url(short_url):
resp = requests.get(short_url, allow_redirects=False)
return resp.headers['location']
def replace_short_urls(text):
for domain in (
domain
for domain in DOMAINS
if domain in text
):
pattern = PATTERN.format(domain)
text = re.sub(pattern, lambda m: expand_short_url(m.group(0)), text)
return text
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment