H.E
H.E

Reputation: 57

Building graph from string in python

I have a csv file that looks like this:

No                    String

1                     A B A A B C D E E C F

1                     B B B C M F G

1                     A A M V 

2                     H C A A A B B N M F 

2                     N M H D D B A F F N M N

3                     A C M G F F A A A

..                    ....

I would like to convert this file to a graph where it contains nodes: A,B ,C,D,E,F,G,H,M,N,V and edges between them are the value in column 'No' with considering of loop.

Any hints would be appreciated.

Upvotes: 0

Views: 1595

Answers (1)

HizClick
HizClick

Reputation: 61

I just saw your question while browsing it may be late but it maybe helpful First create one digraph and a list Graph = DiGraph() string_list = list # to add all strings

so first you have to read the file and put it in any data structure you prefer. In this case I put it in dictionary

with open(file_path, 'r', encoding='utf-8') as csvfile:
    reader = DictReader(csvfile)
    data = [dict(x) for x in reader]

after that

    for row in data: # for each item in the dictionary 
        string_list.extend(row['String'].split(' ')) # add a list of strings which are separated by "space" into a list. So that, you can access each character
         for char in string_list: # for each element in the list (each character)
            Graph.add_edge(row['No'], char) (create an edge between each "No" with each character )

print(Graph.edges())

this should work

Upvotes: 1

Related Questions