Skip to content

Instantly share code, notes, and snippets.

Last active August 29, 2015 14:07
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
import sys
if sys.version_info[0] == 3:
from io import StringIO
from cStringIO import StringIO
def replace_entities(text, grouped_entities, **replacers):
entities = []
for entity_type, entity_list in grouped_entities.items():
replacer = replacers.get(entity_type)
if replacer is None:
for entity in entity_list:
entity_pair = (entity['indices'], replacer(entity))
entities.sort(key = lambda x: x[0][0])
output = StringIO()
last_idx = 0
for entity_pair in entities:
indices, entity = entity_pair
i, j = indices
output.write(text[last_idx : i])
last_idx = j
output.write(text[last_idx :])
return output.getvalue()
def tweet_replace_links(tweet):
def url_replacer(url):
return '<a href="%s">%s</a>' % (url['expanded_url'], url['display_url'])
return replace_entities(tweet['text'], tweet['entities'], urls = url_replacer)
tweet = {
"text": "Today, Twitter is updating embedded Tweets to enable a richer photo experience:",
"entities": {
"hashtags": [],
"symbols": [],
"urls": [{
"url": "",
"expanded_url": "",
"display_url": "",
"indices": [80, 103]
"user_mentions": []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment