Created
April 4, 2012 16:16
-
-
Save wynemo/2303420 to your computer and use it in GitHub Desktop.
sub url in twitter text
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
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