-2

I have the data in .txt format separated by spaces and line breaks. Here is some of them.

1 2 1082040961
3 4 1082155839
5 2 1082414391
6 7 1082439619
8 7 1082439756

This data represents temporal graphs, G = (u, v, t), where u, v, and t means there is an edge from node u to node v with timestamp t.

I want to visualize these data using Python's library pathpy. They must be coded like below to add an edge.

t.add_edge('1', '2', 1082040961)
t.add_edge('3', '4', 1082155839)
t.add_edge('5', '2', 1082414391)
t.add_edge('6', '7', 1082439619)
t.add_edge('8', '7', 1082439756)

But there are a lot of edges in the data. So I need a smart way to handle this. How should I code this tuple transformation?

4 Answers 4

3

You can iterate over the dataset in the following way:

with open(filename.txt) as f:
    for line in f:
        data = line.strip().split()
        t.add_edge(data[0], data[1], int(data[2])

Please let me know if this works or if you have any other questions.

2
  • 1
    't.add_edge(data[0], data[1], int(data[2])' Does this part encoding in single quotes for the data in the first and second columns?
    – port trum
    Nov 23, 2019 at 12:02
  • 1
    yes, data[0], data[1] and data[2] are all strings and hence the first two can be passed to the function. Nov 23, 2019 at 18:02
1

Not sure if that's what you need, but there's a read_file function in pathpy library. It allows to construct a new TemporalNetwork object from a file of similar format to yours. Check this commit.

0
0

You can use pandas library also.

import pandas as pd

path = r"C:\txt\file\path"

df = pd.read_fwf(path, header=None)
length = len(df.index)

for i in range(length):
    t.add_edge(df[df.columns[0]][i], df[df.columns[1]][i], df[df.columns[2]][i])
4
  • 1
    Why are you marking the string in path with an r prefix? That prefix marks the start of a regular expression.
    – accdias
    Nov 22, 2019 at 12:48
  • 1
    To avoid unicode error. For example, my path is "C:\Users\berka\Desktop\dene.txt" and \b causes unicode error. Nov 22, 2019 at 12:55
  • 2
    @accdias - the r doesn't mean it's a regular expression, it means it's a raw string, which are often used for regular expressions, but in this case it just saves having to manually escape the `\` in the path to filename.
    – sjw
    Nov 22, 2019 at 12:55
  • 2
    @thesilkworm, Oh! I see. Thanks for the explanation. I always used it thinking it was a marker for a regular expression and now it makes a lot more sense.
    – accdias
    Nov 22, 2019 at 12:57
0

This may help too:

print [t.add_edge(str(data[0]),str(data[2]),int(data[4:-1])) for data in open("filename.txt") if data.strip().split(" ")]

Not the answer you're looking for? Browse other questions tagged or ask your own question.