Skip to content

Instantly share code, notes, and snippets.

@wynemo
Created April 4, 2012 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wynemo/2303420 to your computer and use it in GitHub Desktop.
Save wynemo/2303420 to your computer and use it in GitHub Desktop.
sub url in twitter text
def sub_url(self,str1):
import json
rv = str1
try:
o = json.loads(str1)
changed = 0
if isinstance(o,list):
for i,each in enumerate(o):
if each.has_key('text') and each.has_key('entities') and each['entities'].has_key('urls'):
text = each['text']
added_len = 0
_changed = 0
for j,url in enumerate(each['entities']['urls']):
if url:
pos1 = url['indices'][0]
pos2 = url['indices'][1]
text = text[:pos1 + added_len] + url['expanded_url'] + text[pos2 + added_len:]
url['url'] = url['expanded_url']
indices1 = [pos1 + added_len,pos1 + len(url['expanded_url']) + added_len]
url['indices'] = indices1
each['entities']['urls'][j] = url
added_len += len(url['expanded_url']) - pos2 + pos1
_changed = 1
if 0 != _changed:
each['text'] = text
o[i] = each
changed = 1
if changed == 1:
#print json.dumps(o,indent=4)
rv = json.dumps(o)
except:
pass
return rv
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment