Frage

I'm trying to add edges between nodes.

I have a text file which I have put into a list. The first list contains this:

          Title           ,            Rating

[('"$weepstake$" (1979) {(#1.2)}', '10.0'), 
('"\'Til Death Do Us Part" (2006) {Pilot(#1.0)}', '3.7'), 
('"\'Conversations with My Wife\'" (2010)', '4.2'), 
('"\'Da Kink in My Hair" (2007)', '4.2').....much more here ]

I want to create nodes labeled with all the titles and when two titles have the same rating, then I want to create an edge between them, so I - in the end - get all titles with rating 10.0 together in one network and so on.

My code so far:

import networkx as nx
import string
from sys import maxint
import csv
import pprint
import re

def printStuff(labels,dG):
    for index, node in enumerate(dG.nodes()):
        print '%s:%d\n' % (labels[index],dG.node[node]['count']) 

str1 = titleList
#print str1

get_user_info = titleList1


dG = nx.DiGraph()




for i, word in enumerate(str1):

    try:
        next_word = str1[i]
        if not dG.has_node(word):
            dG.add_node(word)
            dG.node[word]['count'] = 1
        else:
            dG.node[word]['count'] += 1
        if not dG.has_node(next_word):
            dG.add_node(next_word)
            dG.node[next_word]['count'] = 0

        if not dG.has_edge(word, next_word):
            dG.add_edge(word, next_word, weight=0)
        else:
            dG.edge[word][next_word]['weight'] += 1
    except IndexError:
        if not dG.has_node(word):
            dG.add_node(word)
            dG.node[word]['count'] = 1
        else:
            dG.node[word]['count'] += 1
    except:
        raise

    printStuff(titleList, dG)

Output:

    10.0:1

10.0:1

3.7:1

10.0:1

3.7:1

4.2:1

10.0:1

3.7:1

4.2:1

4.2:1

And for edges:

for edge in dG.edges():
    print '%s:%d\n' % (edge,dG.edge[edge[0]][edge[1]]['weight'])

Output:

(('"\'Conversations with My Wife\'" (2010)', '4.2'), ('"\'Conversations with My Wife\'"   (2010)', '4.2')):0

(('"\'Da Kink in My Hair" (2007)', '4.2'), ('"\'Da Kink in My Hair" (2007)', '4.2')):0

(('"$weepstake$" (1979) {(#1.2)}', '10.0'), ('"$weepstake$" (1979) {(#1.2)}', '10.0')):0

(('"\'Til Death Do Us Part" (2006) {Pilot (#1.0)}', '3.7'), ('"\'Til Death Do Us Part" (2006) {Pilot (#1.0)}', '3.7')):0
War es hilfreich?

Lösung

How about this:

data = [('"$weepstake$" (1979) {(#1.2)}', '10.0'), 
('"\'Til Death Do Us Part" (2006) {Pilot(#1.0)}', '3.7'), 
('"\'Conversations with My Wife\'" (2010)', '4.2'), 
('"\'Da Kink in My Hair" (2007)', '4.2')]

import networkx as nx
G = nx.Graph()
G.add_edges_from(data)
nx.draw(G)

enter image description here

if you want a count of edges from a score.

len(G.edges('4.2'))

2

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top