예제 #1
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("------\nGerando uma rede direcionada.")
        grafo = nx.DiGraph()
    else:
        print("------\nGerando uma rede não direcionada.")
        grafo = nx.Graph()

    # 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(f"erro {e}")
        sys.exit()
    cont = 0
    for tweet in tweets:
        destino = None
        try:
            cont += 1
            destino = tweet['user']['screen_name']
        except Exception:
            pass
        try:
            origem = tweet['retweeted_status']['user']['screen_name']
        except Exception:
            origem = None
        if destino is not None and origem is not None:
            grafo.add_edge(origem, destino)

    print(f"Com: {cont} tweets")
    print("Utilizando: Retweets")
    print(f"Nome da Rede: {nome_rede}")
    print(f"Originada da Colecao: {nome_colecao}\n--------")
    print(f"Sumário da Rede: \n{nx.info(grafo)} \n------")
    try:
        arquivo = open(network_path + "sumario_" + nome_rede, "w")
    except FileNotFoundError:
        os.mkdir(network_path)
        arquivo = open(network_path + "sumario_" + nome_rede, "w")
    arquivo.write(str(nx.info(grafo)))
    arquivo.close()
    nx.write_gml(grafo, network_path + nome_rede + ".gml")
    grafo_ids = nx.convert_node_labels_to_integers(grafo)
    # gera traducao de nome para números
    cont = 0
    with open(network_path + "traducao_"+nome_rede, 'a+') as arq:
        for i in grafo:
            arq.write(i+":"+str(cont)+"\n")
            cont += 1
    nx.write_edgelist(grafo_ids,
                      network_path + nome_rede + ".edgelist", data=False)
예제 #2
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:
            pass
    return lista_tweets
예제 #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:
            # print("erro",e)
            pass
    # print(len(lista_tweets))
    return lista_tweets
예제 #4
0
def main(nome_base, colecao, lista_nos, nome_rede):
    cliente = bd.inicia_conexao()
    colecao = bd.carregar_banco(cliente, nome_base, colecao)

    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", len(lista))
    arq_retweets = open(f'{centrality_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(f'{centrality_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")

    # fix size adding zero
    if len(lista_curtidas) != len(lista_degree):
        lista_curtidas = fix_size(lista_curtidas, len(lista_degree))
    if len(lista_retweets) != len(lista_degree):
        lista_retweets = fix_size(lista_retweets, len(lista_degree))

    print(len(lista_curtidas), len(lista_retweets), len(lista_betweenness),
          len(lista_degree), len(lista_pagerank))
    salvar_csv(nome_rede, lista_betweenness, lista_retweets, lista_curtidas,
               lista_degree, lista_pagerank)
    arq_curtidas.close()
예제 #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(centrality_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(centrality_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()