I'm quite lost with this one, im currently making a program that gets an input from a .txt document, the first line says: "From:0 To:4", and my goal is to get the "0" and "4" values.

This is what im currently doing:

with open('graph.txt') as matrix:  
    linea = matrix.readlines()  
    for line in linea:  
         if line.startswith('From:'):  
             start = line.rsplit(':')[-1].strip() 
             start= int(start,10)                      
         elif line.__contains__('To:'):  
              end = line.split(':')[-1].strip()  
              end = int(end,10)

I made it this way because before the "from:" and "to:" were in two different lines, but I needed to set them in the same one. The prolem righ now is that whenever i run the code I got "NameError: name 'end' is not defined".

5 Answers

0
Austin On

The easiest flexible way is to use a regex:

import re

with open('graph.txt') as matrix:
    for line in matrix: 
        from_, to = re.findall(r':(\d+)', line)

This fetches the two numeric data to two variables from_ and to.

0
thehole On

The main problem with your code is the elif -- since the if block executes, elif never does, so end never gets set. Changing elif to if will result in both if blocks executing, so both variables get set.

You'll end up with a bit of repeated code, though, which is frowned upon (DRY)

@Boris's comment is important, too, you don't have to call __contains__

I came up with a different regex than Austin's, which splits on spaces and colons to tokenize the line:

import re
with open('matrix.txt') as matrix:
    linea = matrix.readlines()
    for line in linea:
        split = re.split('\s|:', line)
        start, end = (split[1], split[3])
        print(f"{start} {end}")
-1
Fizzlebert On

Oneliner

(_, begin), (_, end) = list(map(lambda s: s.split(":"), line.split()))

First I'm splitting the line in two using the builtin through the built in split. Next I'm making use of the map function to apply a lambda which further splits the line into four stages, again using the split function of strings in python. Lastly the values are stored as begin and end using tuple unpacking.

Hope this didn't go over your head and helps you.

-2
Bunny On

The code below will read what you want.

with open('graph.txt') as matrix:  
    linea = matrix.readlines()  
    for line in linea:  
        if line.startswith('From:'):  
            start = line.split('From:')
            #start= int(start,10)
            print(start)
            for a in start:
                if a.__contains__('To:'):
                    b = a.split('To:')
                    print(b[0].strip(),b[1].strip())

And a second option which is similar to your code:

with open('graph.txt') as matrix:  
    linea = matrix.readlines()

    for line in linea:
        d = line.split(' ')
        print(d)
        for elm in d:
            if elm.__contains__('From:'):
                print(elm.split(':')[-1].strip())
            elif elm.__contains__('To:'):
                print(elm.split(':')[-1].strip())
0
Devesh Kumar Singh On

You should regex to extract all possible numbers from the string. The code below should work irrespective of any string around the numbers.

import re

with open('graph.txt') as matrix:
    for line in matrix:
        start, end = re.findall(r'(\d+)', line)
        print(start)
        print(end)

So if the file looks like:

From:  0 To:  4
From:0 To:   4
From:  123To:  456
From 12 to 34

The output will be

0
4
0
4
123
456
12
34

As you can see, all numbers were extracted, irrespective of the format of the string.