Skip to content

Instantly share code, notes, and snippets.

@mdornseif
Created April 30, 2012 08:14
Show Gist options
  • Save mdornseif/2556488 to your computer and use it in GitHub Desktop.
Save mdornseif/2556488 to your computer and use it in GitHub Desktop.
URL verkürzen
# Verkürzen ein URL per call zu is.gd
def _tiny_url(url):
"""Does a API call to is.gd to get a shortened URL."""
apiurl = 'http://is.gd/api.php?longurl='
_status, _headers, content = huTools.http.fetch(apiurl + url, ua='cs.notifications')
return content
# Alle URLs in einem Text verkürzen
def _content_tiny_url(content):
"""Converts all URLS in content to TinyURLs."""
regex_url = r'https?:\/\/([\w.]+\/?)\S*'
for match in re.finditer(regex_url, content):
url = match.group(0)
content = content.replace(url, _tiny_url(url))
return content
# Verkürzene ines Tetes auf höchstens maxlen (140) Zeichen
def shorten(text, maxlen=140):
"""Shortens a text to be less than <maxlen>."""
# Verkürzen ist nur nötig, wenn der Text zu lang ist
if len(text) > maxlen:
# Zunächt alle URLs verkürzen
text = _content_tiny_url(text)
# Nun kann es immer noch sein, dass der Text zu lang ist. Wir übernehmen deswegen
# nun wortweise text, bis er (eventuell) zu lang ist.
textsegments = text.split()
output = []
while textsegments and (len(' '.join(output + [textsegments[0]])) <= maxlen):
output.append(textsegments.pop(0))
if output:
return (' '.join(output))[:maxlen]
return text[:maxlen]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment