wynemo
4/4/2012 - 4:16 PM

sub url in twitter text

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