Last active
August 29, 2015 14:20
-
-
Save movEAX/7ca78153e5eaf0eafd98 to your computer and use it in GitHub Desktop.
Replace short links in text to full links
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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