Exemplo n.º 1
0
def carrega_tweet_mongo(nome_base, colecao):
    """Carrega e realiza a chamada de limpeza dos tweets"""
    cliente = bd.inicia_conexao()
    colecao = bd.carregar_banco(cliente, nome_base, colecao)
    tweets = tweets = colecao.find({})
    lista_tweets = []
    for tweet in tweets:
        try:
            full_tweet = tweet["extended_tweet"]["full_text"]
            if len(full_tweet) > 1:
                lista_tweets.append(pre_processamento(full_tweet))
        except Exception as e:
            pass
    return lista_tweets
Exemplo n.º 2
0
def main(banco_dados, colecao):
    """Coletor web"""
    cliente = db.inicia_conexao()
    conector = db.carregar_banco(cliente, banco_dados, colecao)
    tweets = conector.find({})

    for tweet in tweets:
        id_tweet = tweet['id_str']
        usuario_tweet = tweet['user']['screen_name']
        try:
            comment.get_data(usuario_tweet, id_tweet)
        # pylint: disable= broad-except
        except Exception as exc:
            print("A coleta foi encerrada.")
            print(f"Erro {exc}")
            sys.exit()
Exemplo n.º 3
0
def carrega_tweet_mongo(banco, colecao):
    """Carrega e realiza a chamada de limpeza dos tweets"""
    print(banco, colecao)
    cliente = bd.inicia_conexao()

    # nome termo,collection
    colecao = bd.carregar_banco(cliente, banco, colecao)
    tweets = tweets = colecao.find({})
    lista_tweets = []
    for tweet in tweets:
        # print(tweet)
        try:
            full_tweet = tweet["extended_tweet"]["full_text"]
            if len(full_tweet) > 1:
                lista_tweets.append(
                    pre_processamento.pre_processing(full_tweet))
        except Exception as e:
            # print("erro",e)
            pass
    # print(len(lista_tweets))
    return lista_tweets
Exemplo n.º 4
0
def main(nome_rede, nome_base, nome_colecao, direcionada, limite_tweets):
    cliente = bd.inicia_conexao()
    colecao = bd.carregar_banco(cliente, nome_base, nome_colecao)
    # grafo não direcionado
    if "True" in direcionada:
        print("Gerando uma rede direcionada.")
        grafo = nx.DiGraph()
    else:
        print("Gerando uma rede não direcionada.")
        grafo = nx.Graph()
    # inica a conexao com twitter
    api = conexao_twitter.inicia_conexao()

    # utilizado para selecionar o titulo
    # contendo a palavra senado maiusculo e minusculo.
    # retorno=colecao.find({"titulo":{"$regex":"senado","$options":"i"}})
    # for i in retorno:
    #     print(i)
    # carrega os tweets da coleção..
    try:
        # limitando o número de tweets utilizado..
        tweets = colecao.find().limit(limite_tweets)
    except Exception as e:
        print(e, "erro")
        exit()
    cont = 0
    for tweet in tweets:
        # print (tweet['user']['screen_name'])
        destino = None
        try:
            # print(tweet)
            cont += 1
            destino = tweet['user']['screen_name']
            # print(origem)
        except Exception as e:
            pass
        try:
            origem = tweet['retweeted_status']['user']['screen_name']
        except Exception as e:
            origem = None
        if destino is not None and origem is not None:
            grafo.add_edge(origem, destino)
    print("------\nGerando a rede com: ", cont, "tweets")
    print("Nome da Rede:", nome_rede)
    print("Originada da Colecao:", nome_colecao, "\n--------")
    print("Sumário da Rede:\n", nx.info(grafo), "\n------")
    try:
        arquivo = open(caminho_base + "sumario_" + nome_rede, "w")
    except FileNotFoundError as e:
        os.mkdir(caminho_base)
        arquivo = open(caminho_base + "sumario_" + nome_rede, "w")
    arquivo.write(str(nx.info(grafo)))
    arquivo.close()
    nx.write_gml(grafo, caminho_base + nome_rede + ".gml")
    grafo_ids = nx.convert_node_labels_to_integers(grafo)
    # gera traducao de nome para números
    cont = 0
    with open(caminho_base + "traducao_" + nome_rede, 'a+') as arq:
        for i in grafo:
            arq.write(i + ":" + str(cont) + "\n")
            cont += 1
    nx.write_edgelist(grafo_ids,
                      caminho_base + nome_rede + ".edgelist",
                      data=False)
Exemplo n.º 5
0
def main(nome_base, colecao, lista_nos, nome_rede):
    cliente = bd.inicia_conexao()
    colecao = bd.carregar_banco(cliente, nome_base, colecao)

    # inica a conexao com twitter
    # api = conexao.inicia_conexao()

    # utilizado para selecionar o titulo contendo
    # a palavra senado maiusculo e minúsculo.
    # retorno=colecao.find({"titulo":{"$regex":"senado","$options":"i"}})
    # for i in retorno:
    #     print(i)
    # print("Dados",nome_base,nome_colecao,lista_nos,nome_rede)
    tweets = []
    for nome_no in lista_nos:
        tweets.append(
            colecao.find(
                {"user.screen_name": {
                    "$regex": nome_no,
                    "$options": "i"
                }}))

    user = {}
    tweets = prepara_tweets(tweets)
    user = consulta_origem(user, tweets)
    print(user)

    user = consulta(user, tweets)
    print("pos", user)

    lista = []
    for i in user:
        # Nome, Retweets, Curtidas
        lista.append([i, user[i][0], user[i][1]])
    print("Retweets")
    arq_retweets = open(path + "sementes_retweets_" + nome_rede, "w")
    retorno = sorted(lista, key=key_retweets_dic, reverse=True)
    # print(retorno)
    # print("LN",lista_nos)
    lista_retweets = []
    lista_curtidas = []
    lista_betweenness = []
    lista_degree = []
    lista_pagerank = []
    grafo = carrega_grafo(nome_rede)
    lista_pagerank = pagerank(grafo)
    imprimir_sementes(lista_pagerank, "pagerank", nome_rede)
    lista_betweenness = analise_betweenness(grafo)
    imprimir_sementes(lista_betweenness, "Betweenness", nome_rede)
    lista_degree = degree(grafo)
    imprimir_sementes(lista_degree, "Degree", nome_rede)
    for retweets in retorno:
        for no in lista_nos:
            if retweets[0].lower() == no.lower():
                lista_retweets.append(retweets[1])
                arq_retweets.write(str(no) + "\n")
    arq_retweets.close()
    arq_curtidas = open(path + "sementes_curtidas_" + nome_rede, "w")
    print("Curtidas")
    for curtidas in sorted(lista, key=key_curtidas_dic, reverse=True):
        for no in lista_nos:
            if curtidas[0].lower() == no.lower():
                lista_curtidas.append(float(curtidas[2]))
                arq_curtidas.write(str(no) + "\n")
    print(
        len(lista_curtidas),
        len(lista_retweets),
        len(lista_betweenness),
        len(lista_degree),
        len(lista_degree),
    )
    salvar_csv(
        nome_rede,
        lista_betweenness,
        lista_retweets,
        lista_curtidas,
        lista_degree,
        lista_pagerank,
    )
    arq_curtidas.close()