In [1]:
import pandas as pd
import json,csv,re,os,sys,glob,dateutil,collections,operator,time,itertools,fuzzy,difflib,bisect
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rcParams['axes.titlesize'] = 18
mpl.rcParams['axes.labelsize'] = 14
mpl.rcParams['legend.fontsize'] = 12
%matplotlib inline

In [2]:
import sys
sys.path.append('/mnt/home/ubuntu/projects/tools/')
from gp_colours import *

In [3]:
plotColours=[gpBlue,gpDarkBlue,gpRed,'black']
plotColours=['#e41a1c','#377eb8','#4daf4a','#984ea3','#ff7f00','#ffff53','#a65628','#f781bf','#9999f9']
#plotColours.extend(plotColours)
'''
def colours():
    n=0
    for c in plotColours:
        yield c
    # Give me a new colour, one at a time
coloursClass=colours()
'''
colors=itertools.cycle(plotColours)
# We need a whole bunch of colours, so repeat them

In [4]:
topics=[u'Discrimination',u'Prevention',u'Campaign',u'Testing']

In [99]:
nTotal=0
nErrors=0
nTopicErrors=0
nFollowerError=0
nInRange=0
tweetCounter=collections.defaultdict(int)
# Count each tweet in one big bucket

tweetTopicCounter={}
for t in topics:
    tweetTopicCounter[t]=collections.defaultdict(int)
# Count each tweet by topic

topFollowers=[(-1,-1) for i in range(10)]
# This is a list, it holds 10 tweet id's with
# most number of followers
currentTopFollower=-1
# Keep track of minimum value in top 10
# Optimises loop

topTopicFollowers={t:[(-1,-1) for i in range(10)] for t in topics}
# Dictionary of lists

currentTopTopicFollowers={t:-1 for t in topics}
# Likewise keep a record of current largest
# follower count

nRetweet=0
    
for dir in glob.glob('../data/stream'):
    print dir
    for f in glob.glob(dir+'/Data*json'):
        for line in open(f,'r').read().decode('utf-8').split('\n'):
            nTotal+=1
            isRetweet=False
            
            tweet=json.loads(line)
            # tweetTime=dt.datetime.strptime(tweet['interaction']['created_at'],'%a, %d %b %Y %H:%M:%S +0000')
            # TODO try twitter.retweeted.created_at first, if not use interaction.created_at
            # dayDiff=(tweetTime-dt.datetime.now()).days
            # Tue, 20 May 2014 23:57:56 +0000

            if True:
            # Filter here by language/date
                nInRange+=1
                try:
                    
                    try:
                        id=tweet['twitter']['retweeted']['id']  # TODO: check if this is a bug, should it not be "retweet" (instead of retweeted)?
                        isRetweet=True
                    except:
                        id=tweet['twitter']['id']
                    
                    content=tweet['interaction']['content'].encode('utf-8').replace('\n',' ')
                    
                    if re.search(r'\bRT ',content):
                        nRetweet+=1
                        print content

                    tweetCounter[(content,id)]+=1
                except:
                    nErrors+=1
                ##########################################################
                try:
                    tweetTopics=tweet['interaction']['tag_tree']['topic']
                    for topic in tweetTopics:
                        tweetTopicCounter[topic][(content,id)]+=1
                except:
                    tweetTopicCounter[u'None'][(content,id)]+=1
                    nTopicErrors+=1
                # Count tweets by topic
                ##########################################################
                try:                
                    try:
                        nFollowers=tweet['twitter']['user']['followers_count']
                    except:
                        nFollowers=tweet['twitter']['retweet']['user']['followers_count']
                    
                    if nFollowers>currentTopFollower and not isRetweet:
                        bisect.insort(topFollowers,(nFollowers,id))
                        currentTopFollower=topFollowers[0][0]
                        # Insert tweet to maintain order
                        # if new number of followers is larger than lowest value
                        if len(topFollowers)>10:topFollowers=topFollowers[-10:]
                        # Allow lower values to drop out
                    
                    for topic in tweetTopics:
                        if nFollowers>currentTopTopicFollowers[topic] and not isRetweet:
#                            print 'INSERTING TO',topic
#                            print nFollowers,currentTopTopicFollowers[topic]
                            
                            currentTopTopicFollowers[topic]=topTopicFollowers[topic][0][0]                            
                            bisect.insort(topTopicFollowers[topic],(nFollowers,id))
                            if len(topTopicFollowers[topic])>10:topTopicFollowers[topic]=topTopicFollowers[topic][-10:]
#                            print topTopicFollowers[topic]
#                            print ''
                    
                except:
                    nFollowerError+=1
                # Get tweets with top followers
                ##########################################################

                
    print '\t',nErrors,nTopicErrors,nFollowerError,nInRange,nTotal
#print 'ERRORS',nErrors


../data/stream
RT O governo podia parar de distribuir camisinha grátis e dar wi-fi já que a gente não transa mesmo
Vinheta Luis Roberto: esse negro maravilhoso. RT @piroquio: Segundo o Roby Porto, o Nenê acabou de socar com vontade. Isso é uma bichona.
RT @sliverfuck ai prefiro baixa ai prefiro alta ai prefiro gorda ai prefiro magra ai prefiro loira OW PORRA É TUDO MULHER SEU VIADINHO FDP
Sim, é real! (Esse daí virou boiola!) RT @CBFudeu: Essa foto é real? http://t.co/tgbRDEHJFu
Miga,não tenho nojo,tenho medo mesmo @azizizazizo RT Francisco,se decide.Cê é vagabunda ou cê tem nojo de sexo
Utilidade pública!  RT "@pavarini: Camisinha que mata vírus da Aids deve começar a ser vendida nos próximos meses http://t.co/SX5r6l1Te7"
Hum, boiola RT @HmNielson Minha mãe me deu luz e eu tô brilhando até hoje.
Deve ser uma bichona RT @Betinhavaila: Meu vizinho ta gritando tanto..acho que ele deve ter enfiado um toco no cu
BOIOLA RT @itsdirrty: se eu for pro xvideos dar play em algum porno da Gretchen eu vou rir ao invés de fazer as necessidades
@bandmichael nem eu dando RT no coitado do francís você ver ele na tl, QUE ODIO DE VC BICHA
Parem de dar RT , todos sabemos que o alisson era um baitola aidético
Bichona!!! #UF RT @Mr_Testicles Altidore Pode fazer o tratamento aqui em casa. Trato esse Negão Bombom com comida na boca!!!
RT @felipeneto luto contra o machismo sim inclusive amo mulheres (menos aquela feminazi vagabunda que discorda de mim)
Bichona RT @VEJA: Assim como o livro, ‘A Culpa É das Estrelas’ é filme para ser sentido http://t.co/gh6leNMaNw
Se continuar dando RT nesses aidéticos vou te dar unfollow @feehcaetano ;*
Inveja do Enem RT @porramuz: Usando Camisinha No Enem Pq Ele Vai Me Foder tm
RT Beber no bico é nojento'' mas de engolir gozo tu nao tem nojo ne vadia
MACACO SIMÃO, TU QUER CHAMAR O CARA DE BICHONA, DIZ LOGO! RT "@jose_simao: O goleiro ingles parece o Boy George!"
Ou comunista. RT @NaoSouHomofobco Adoro essa gente que acha que qualquer pessoa que luta contra a homofobia é, obrigatoriamente, petista.
HUUUUUUUUUUM BOIOLA RT @FutebolZueiroPA Neuer me engravida
Bichona. RT @tupagao: Feliz em ver o Neymar hoje. Adorei o cabelo novo dele!
Simples: coisa de viado. RT "@OscarFilho: Pelo amor de deusss, alguém me explica isso? http://t.co/ybh7GmY8sd"
Bichona ♥ RT @felipelisboa89: ♪ Olha a cabeleira do David! Será que ele é bi? Será que ele é bi?!?! ♫ http://t.co/TcrONq4ma9
#RT "@ISSOLHEM: ESSA VAGABUNDA DISSE QUE TEM NOJO DE QUEM TEM CANCER QUE PUTA DO RKRL https://t.co/r7taJekBBe"
essa coca é fanta RT @D_Romariio: SNEIJDER, ME CHAMA DE BOLA E ME TRATE COM CARINHO
Cade o boiola do @Joaominerino que ainda não deu RT nos meus tweets?!
BICHONA!!! RT @giuliano_reis  @talissu PODE ATÉ SER
Bichona! RT @sepdeco: Howard belo goleiro!
RT: "@_tallyto vocês são uns boiolas dando RT assim"
Que bixona esse Aneir RT @Vinicius_Aneir: @karlabarcelos13 @rafaelnicacio09 Kid Bengala???? ADOROOOO
Pelo menos sou um boiola com dinheiro RT @nugguetor: Vans é marca de boiola.
#WTF RT @folha_com: Presos chilenos assistirão filmes gays para erradicar homofobia das prisões. http://t.co/lVyl5D8gdB”
"@vinnysacramento: "Ainda bem que eu não tô lá" RT @vanessatocha: http://t.co/7eFeCxXp9s" Morde fronha do caralho!
BICHONA RT @cainafeitosa: O bixo fala "esses negros maravilhosos" depois "ai que delicia esse gol"
RT @g_uilhermemoura: Ultimamente ando muito boiola. Normal
	0 0 0 8478 8478

In [98]:
nRetweet


Out[98]:
35

In [86]:
topTopicFollowers


Out[86]:
{u'Campaign': [(848, u'476513453784719360'),
  (908, u'474723884466720768'),
  (923, u'475934449130287104'),
  (931, u'476613970535919616'),
  (1362, u'477223271826345984'),
  (1372, u'480816460722221057'),
  (4223, u'489811100498542592'),
  (12998, u'476530533460373504'),
  (52874, u'473456993143779328'),
  (53377, u'483954067371089921')],
 u'Discrimination': [(53556, u'490974650177191936'),
  (67665, u'491742130688503808'),
  (69349, u'481270228723068929'),
  (74711, u'494745901173571584'),
  (110319, u'474886795629707264'),
  (120436, u'478721213037289473'),
  (120437, u'478620629420482561'),
  (186672, u'488397461862752257'),
  (187531, u'480198386663313408'),
  (325198, u'485517184425541632')],
 u'Prevention': [(16258, u'481915742997450752'),
  (19147, u'483050018459615233'),
  (21648, u'487117860410769408'),
  (22363, u'477175186949554176'),
  (23776, u'493603772074307584'),
  (36594, u'492063486319788032'),
  (41679, u'476725183324372992'),
  (46020, u'476558745255038976'),
  (75979, u'492429904244662275'),
  (188586, u'492454865642463233')],
 u'Testing': [(437, u'494554301797531649'),
  (461, u'474895557727887360'),
  (734, u'482408722661392385'),
  (805, u'478579971624288256'),
  (1132, u'483774700049690624'),
  (1240, u'481112724647473152'),
  (1688, u'478912531814445056'),
  (1841, u'482267079757025281'),
  (4405, u'487430764255248384'),
  (5689, u'481765667239374848')]}

In [53]:
test={'a':(1,2),'b':(3,1)}
sorted(test.iteritems(),key=lambda x:x[1][-1])


Out[53]:
[('b', (3, 1)), ('a', (1, 2))]

In [87]:
test=tweetCounter.items()[0:5]
test


Out[87]:
[(('boiola', u'481428336074584064'), 1),
 (('"Ela al\xc3\xa9m de bandida \xc3\xa9 vagabunda". Gente j\xc3\xa1 com \xc3\xb3dio da  novela.',
   u'491755024574582784'),
  1),
 (('@JordanHorn_ o viado t\xc3\xa1 online no face e no whats... N\xc3\xa3o fala comigo desde as 19:00... To com \xc3\xb3dio!',
   u'483104871093391360'),
  1),
 (('Ranked tinha que dar de jogar 5 amigos, s\xc3\xb3 pego nego aid\xc3\xa9tico',
   u'493501087098634240'),
  1),
 (('Se eu posso pegar camisinha de gra\xc3\xa7a no posto devia poder pegar cigarro na padaria.',
   u'485603567970320384'),
  1)]

In [91]:
sortedTweets=sorted(tweetCounter.iteritems(),key=lambda x:x[1])
#sortedTweets.reverse()
for t in sortedTweets[0:20]:
    print t[1],'\t',t[0][0],t[0][1]


1 	boiola 481428336074584064
1 	"Ela além de bandida é vagabunda". Gente já com ódio da  novela. 491755024574582784
1 	@JordanHorn_ o viado tá online no face e no whats... Não fala comigo desde as 19:00... To com ódio! 483104871093391360
1 	Ranked tinha que dar de jogar 5 amigos, só pego nego aidético 493501087098634240
1 	Se eu posso pegar camisinha de graça no posto devia poder pegar cigarro na padaria. 485603567970320384
1 	@Thali_Beulke @pqqjay eu não discuto com a thali, arrebento ela mesmo, trate de comprar nossa camisinha 482026313969307648
1 	tenho nojo de sapatão 487459720434057217
1 	Q coisa de viado kkkkkkk 480134488186691584
1 	Falar ppk é coisa de viado cabaço 480706333105483778
1 	@olapessouinha sim I'AM BOIOLA o vinho n me fez bem kkkk 476182855786430464
1 	@SPachec0 pra trepa cmg tem que te disposição , agora to usando camisinha de limão 😂😂 487656698333888512
1 	the boy with the thorn on his side (a bichona da festa) 494670161606373376
1 	homossexualismo eu sei q n é doença mas sdd tô começando a achar q pode ser 493168421543374848
1 	Nao sei os homens mas eu nao vejo problema se a mina tem selulite ou estria na verdade acho q cara q liga pra isso eh muito boiola na moral 493987808760303616
1 	@omfglari QUEM MANDA NAO USAR CAMISINHA 494333636838453248
1 	Raspar as axilas não é coisa de viado. 476190283089334272
1 	que isso bichona 485852261932101633
1 	tenho nojo de vcs q tão fazendo piadinha com a virgindade do david, caralho se ele fosse putão e metia todo dia em uma vcs reclamam + 488775315318378496
1 	@seilacabello bicha ridícula dona do meu ódio 488816489206931456
1 	se vocês é esquisito assim """normal""" imagina se usar a olla com efeito retardante 486317079772278784

In [61]:
sortedTweets=sorted(tweetCounter.iteritems(), key=operator.itemgetter(1))
sortedTweets.reverse()
outFile=csv.writer(open('../web/data/top-tweets/portuguese.all.top.retweet','w'),delimiter='\t')

for t in sortedTweets[0:10]:
    print t[1],'\t',t[0]
    outFile.writerow([t[0][1]])
# Write out top tweet ids for all tweets


1 	('OLHA O N\xc3\x8dVEL DAS MINHAS AMIZADES OAKAOKAOAKAOK BICHONA \xe2\x99\xa1 http://t.co/p8eQnIC7dk', u'491421238137733120')
1 	('@soaress_fe vadia \xc3\xa9 tua av\xc3\xb3! Boiola! Nao coloco nem pra mim, que dira pra voc\xc3\xaa...', u'473814288469995521')
1 	('Q nojo dessas vadia q dizem ser minhas amigas, mds QUE NOJO', u'485438481712562176')
1 	('@shogoki_ o problema nem \xc3\xa9 a pessoa,  \xc3\xa9 a quest\xc3\xa3o "eu usei camisinha, n\xc3\xa9?" :P', u'489262817158365184')
1 	('NOSSA.. QUERO SOCAR O ALEM\xc3\x83O.. QUANDO EU VOLTAR P CASA ELE VAI SE VER.. AIN QUE \xc3\x93DIO, VIADO !', u'483101519831896064')
1 	('N\xc3\x83O TRAVA PORRA AI Q \xc3\x93DIO', u'485462740975505408')
1 	('viados miser\xc3\xa1veis de merda tomara que todos morram exceto ryan, jon e spencer', u'477910828277305344')
1 	('S\xc3\xa9rio, eu acho que nunca senti tanto nojo de uma pessoa, como to sentindo dessa vadia', u'481424925044273152')
1 	('rog\xc3\xa9rio eh um boiola', u'474741325557166080')
1 	('Juiz boiola CARALHO', u'486605005907329024')

In [62]:
outFile=csv.writer(open('../web/data/top-tweets/portuguese.all.top.followers','w'),delimiter='\t')
for t in reversed(topFollowers[0:10]):
    outFile.writerow([t[1]])
    print t
# Write out top follower count tweet id's for all tweets


(325198, u'485517184425541632')
(188586, u'492454865642463233')
(187531, u'480198386663313408')
(186672, u'488397461862752257')
(120437, u'478620629420482561')
(120436, u'478721213037289473')
(110319, u'474886795629707264')
(75979, u'492429904244662275')
(74711, u'494745901173571584')
(69349, u'481270228723068929')

In [63]:
test=range(10)
for t in reversed(test[0:10]):print t


9
8
7
6
5
4
3
2
1
0

In [64]:
for k,v in reversed(topTopicFollowers.items()[0:10]):
    print k
    if not k=='None':
        fileName='../web/data/top-tweets/portuguese.'+k+'.top.followers'
        outFile=csv.writer(open(fileName,'w'),delimiter='\t')
        for id in reversed(v):
            outFile.writerow([id[1]])
            print '\t',id
# Write out top follow count tweet ids for tweets, by topic
outFile=None
# Need to flush out file handle
# Sometimes last file doesn't get written otherwise


Prevention
	(188586, u'492454865642463233')
	(75979, u'492429904244662275')
	(46020, u'476558745255038976')
	(41679, u'476725183324372992')
	(36594, u'492063486319788032')
	(23776, u'493603772074307584')
	(22363, u'477175186949554176')
	(21648, u'487117860410769408')
	(19147, u'483050018459615233')
	(16258, u'481915742997450752')
Campaign
	(53377, u'483954067371089921')
	(52874, u'473456993143779328')
	(12998, u'476530533460373504')
	(4223, u'489811100498542592')
	(1372, u'480816460722221057')
	(1362, u'477223271826345984')
	(931, u'476613970535919616')
	(923, u'475934449130287104')
	(908, u'474723884466720768')
	(848, u'476513453784719360')
Testing
	(5689, u'481765667239374848')
	(4405, u'487430764255248384')
	(1841, u'482267079757025281')
	(1688, u'478912531814445056')
	(1240, u'481112724647473152')
	(1132, u'483774700049690624')
	(805, u'478579971624288256')
	(734, u'482408722661392385')
	(461, u'474895557727887360')
	(437, u'494554301797531649')
Discrimination
	(325198, u'485517184425541632')
	(187531, u'480198386663313408')
	(186672, u'488397461862752257')
	(120437, u'478620629420482561')
	(120436, u'478721213037289473')
	(110319, u'474886795629707264')
	(74711, u'494745901173571584')
	(69349, u'481270228723068929')
	(67665, u'491742130688503808')
	(53556, u'490974650177191936')

In [65]:
for k,v in tweetTopicCounter.items():
    if not k=='None':
        sortedTweets=sorted(v.iteritems(),key=lambda x:x[1])
        sortedTweets.reverse()
        fileName='../web/data/top-tweets/portuguese.'+k+'.top.retweet'
        outFile=csv.writer(open(fileName,'w'),delimiter='\t')
        
#        print ''
        print k
#        print '------------'
        
        for t in sortedTweets[0:10]:
            print '\t',t[1],t[0][0],t[0][1]
            outFile.writerow([t[0][1]])
            print 'line',fileName
# Write out top retweeted tweet id's by topic
outFile=None


Discrimination
	1 OLHA O NÍVEL DAS MINHAS AMIZADES OAKAOKAOAKAOK BICHONA ♡ http://t.co/p8eQnIC7dk 491421238137733120
line ../web/data/top-tweets/portuguese.Discrimination.top.retweet
	1 @soaress_fe vadia é tua avó! Boiola! Nao coloco nem pra mim, que dira pra você... 473814288469995521
line ../web/data/top-tweets/portuguese.Discrimination.top.retweet
	1 Q nojo dessas vadia q dizem ser minhas amigas, mds QUE NOJO 485438481712562176
line ../web/data/top-tweets/portuguese.Discrimination.top.retweet
	1 NOSSA.. QUERO SOCAR O ALEMÃO.. QUANDO EU VOLTAR P CASA ELE VAI SE VER.. AIN QUE ÓDIO, VIADO ! 483101519831896064
line ../web/data/top-tweets/portuguese.Discrimination.top.retweet
	1 NÃO TRAVA PORRA AI Q ÓDIO 485462740975505408
line ../web/data/top-tweets/portuguese.Discrimination.top.retweet
	1 viados miseráveis de merda tomara que todos morram exceto ryan, jon e spencer 477910828277305344
line ../web/data/top-tweets/portuguese.Discrimination.top.retweet
	1 Sério, eu acho que nunca senti tanto nojo de uma pessoa, como to sentindo dessa vadia 481424925044273152
line ../web/data/top-tweets/portuguese.Discrimination.top.retweet
	1 rogério eh um boiola 474741325557166080
line ../web/data/top-tweets/portuguese.Discrimination.top.retweet
	1 Juiz boiola CARALHO 486605005907329024
line ../web/data/top-tweets/portuguese.Discrimination.top.retweet
	1 hmmmm boiola 489943747434909697
line ../web/data/top-tweets/portuguese.Discrimination.top.retweet
Testing
	1 @annapaulaaa se joga na piscina da ap e quando sair tem que tomar pílula do dia seguinte e fazer teste de HIV 489468613997641729
line ../web/data/top-tweets/portuguese.Testing.top.retweet
	1 Que tarde maravilhosa pra vc fazer um teste de HIV e dar positivo 481158897945051138
line ../web/data/top-tweets/portuguese.Testing.top.retweet
	1 *viado indo fazer exame de hiv* - fica calmo, pensa positivo 478912531814445056
line ../web/data/top-tweets/portuguese.Testing.top.retweet
	1 pelo menos posso fazer um exame de hiv sem que de positivo vc n 487430764255248384
line ../web/data/top-tweets/portuguese.Testing.top.retweet
	1 Se tivessem hospitais aqui a Espanha poderia fazer um exame de AIDS depois desse estupro 477554572781961216
line ../web/data/top-tweets/portuguese.Testing.top.retweet
	1 "@PedroOtimista Hoje acontece o National #HIV Testing Day (NHTD), fazer o teste do... http://t.co/hYtE2vkf82" Deixa acabar a #CopaDasCopas 482552463615344640
line ../web/data/top-tweets/portuguese.Testing.top.retweet
	1 Minha colega funkeira: "Vou fazer exame hoje" Minha melhor amiga: "exame de aids?"  Eu: KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KK 481765667239374848
line ../web/data/top-tweets/portuguese.Testing.top.retweet
	1 Que tarde maravilhosa pra você fazer um teste de HIV e dar positivo. 481112724647473152
line ../web/data/top-tweets/portuguese.Testing.top.retweet
	1 Eu lembro q quando eles forem transar eles vao parar no comeco e antes de transar vao fazer teste de hiv tipo???????? 483774700049690624
line ../web/data/top-tweets/portuguese.Testing.top.retweet
	1 Se eu fosse o CR7 já ia fazer o teste de HIV agora no intervalo mesmo, vai que o Müller não usou camisinha ne ... 478579971624288256
line ../web/data/top-tweets/portuguese.Testing.top.retweet
Campaign
	1 Hoje, às 10h30, aqui na @topfmsp  #FiqueSabendo!! E neste mês de junho quem responde tudo o que rola… http://t.co/oM8QZC8Dbn 473456993143779328
line ../web/data/top-tweets/portuguese.Campaign.top.retweet
	1 Presidenta @dilmabr firma balon #ProtegeLaMeta con @MichelSidibe @Lzloures @humanloveshuman @Jarbas_Barbosa http://t.co/rel0iKMTTP 476613970535919616
line ../web/data/top-tweets/portuguese.Campaign.top.retweet
	1 Great moments, #UNAIDS Exec.Director Michel Sidibe,Brazil's# FabioMesquita,Djibril Diallo@ProtectTheGoal,Brazil http://t.co/2R1zWzDJ22 475457876300144640
line ../web/data/top-tweets/portuguese.Campaign.top.retweet
	1 “@gbragatwit: @MichelSidibe Graffiti at the Liberdade community. #ProtejaoGol @ProtectTheGoal http://t.co/38oFYdi5FQ” 475934449130287104
line ../web/data/top-tweets/portuguese.Campaign.top.retweet
	1 ❤️ #projetoProtejaoGol #unaids #manaus #amazonas #onu #fifafanfest @ Ponta Negra http://t.co/G89Sz3pS4n 480816460722221057
line ../web/data/top-tweets/portuguese.Campaign.top.retweet
	1 A #CopaDosRefugiados está chegando,proteja o gol mais uma vez #ProtejaoGol #protectthegoal #unaids @MichelSidibe @Lzloures @DDiallo_UNAIDS 491438251542990850
line ../web/data/top-tweets/portuguese.Campaign.top.retweet
	1 #DavidLuiz #unaids refuses to advertise for a famous beer's brand.He knows he is a kids hero and don't want to give a bad testmonial to them 485388959154208768
line ../web/data/top-tweets/portuguese.Campaign.top.retweet
	1 David Luiz convida os fãs do futebol a compromete…: http://t.co/g4JMTl7dP4 #ProtejaOGol 💝✌ 489819605847007232
line ../web/data/top-tweets/portuguese.Campaign.top.retweet
	1 #protejaogol é tendência em Brazil http://t.co/nfHVVtcLQH 489811100498542592
line ../web/data/top-tweets/portuguese.Campaign.top.retweet
	1 #iphone6 #fiquesabendo Muitos rumores sobre o lançamento do novo iPhone circulam pela web, o que deixa… http://t.co/oHYlr1dEE7 491625392101277697
line ../web/data/top-tweets/portuguese.Campaign.top.retweet
Prevention
	1 Comprei akelas camisinha de caipirinha, descubro q eh a camisa do neymar, vo te o nome desta fera no meu pinto bixooo kkkkkkkk 475682475151474688
line ../web/data/top-tweets/portuguese.Prevention.top.retweet
	1 Eu transei bêbado fiz  filho kkkkkkk 493611367791079425
line ../web/data/top-tweets/portuguese.Prevention.top.retweet
	1 imagina transar com uma camisinha di neymar 481181302797123584
line ../web/data/top-tweets/portuguese.Prevention.top.retweet
	1 Acho melhor eu comprar uma camisinha pro meu coração porque ultimamente só tão fodendo com meus sentimentos 481264386192207872
line ../web/data/top-tweets/portuguese.Prevention.top.retweet
	1 Ai ontem fui no posto comprar bebida ne, dai tinha um cara lá de uns 40 anos comprando um pacote de camisinha de cada sabor, fiquei tipo uau 493582511659032576
line ../web/data/top-tweets/portuguese.Prevention.top.retweet
	1 @shogoki_ o problema nem é a pessoa,  é a questão "eu usei camisinha, né?" :P 489262817158365184
line ../web/data/top-tweets/portuguese.Prevention.top.retweet
	1 Sexo oral com camisinha((((((?)))))) 493227249588768768
line ../web/data/top-tweets/portuguese.Prevention.top.retweet
	1 "comente ":*" e quem curtir quer ficar com você na festa da matriz" tomara que vcs peguem uma pessoa que tenha aids e não usem camisinha 478718684677275649
line ../web/data/top-tweets/portuguese.Prevention.top.retweet
	1 Pra fumar meu Marlboro tenho de comprar uma fita durex pra remendar todo ele 492329949987340288
line ../web/data/top-tweets/portuguese.Prevention.top.retweet
	1 Acho melhor eu comprar uma camisinha pro meu coração porque ultimamente só tão fodendo com meus sentimentos 484500418958217216
line ../web/data/top-tweets/portuguese.Prevention.top.retweet

In [41]:
import pickle
outFile=open('top_tweets.dat','w')
pickle.dump(tweetCounter,outFile)
pickle.dump(tweetTopicCounter,outFile)
outFile.close()

In [42]:
topTweets=sortedTweets[0:20]
#topTweets=[(re.sub(r'http:\/\/[a-zA-Z0-9\.\/]+','',t[0]),t[1]) for t in topTweets]

In [17]:
def filterUrl(t):
    return (re.sub(r'http:\/\/[a-zA-Z0-9\.\/]+','',t))
# Strip URLs from tweets so not included in similarity calculation

In [18]:
for i in itertools.combinations(topTweets,2):
    similarity=difflib.SequenceMatcher(None,filterUrl(i[0][0]),filterUrl(i[1][0])).ratio()
    if similarity>0.7:print similarity,'\n',i[0][0],'\n',i[1][0],'\n\n'


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-18-d9caa7049c94> in <module>()
      1 for i in itertools.combinations(topTweets,2):
----> 2     similarity=difflib.SequenceMatcher(None,filterUrl(i[0][0]),filterUrl(i[1][0])).ratio()
      3     if similarity>0.7:print similarity,'\n',i[0][0],'\n',i[1][0],'\n\n'

<ipython-input-17-07da5616b690> in filterUrl(t)
      1 def filterUrl(t):
----> 2     return (re.sub(r'http:\/\/[a-zA-Z0-9\.\/]+','',t))
      3 # Strip URLs from tweets so not included in similarity calculation

/home/ubuntu/anaconda/lib/python2.7/re.pyc in sub(pattern, repl, string, count, flags)
    149     a callable, it's passed the match object and must return
    150     a replacement string to be used."""
--> 151     return _compile(pattern, flags).sub(repl, string, count)
    152 
    153 def subn(pattern, repl, string, count=0, flags=0):

TypeError: expected string or buffer

In [1]:
from IPython.core.display import HTML
styles = open("../css/custom.css", "r").read()
HTML(styles)


Out[1]:

In [ ]: