Jerry Zhao
Jerry Zhao

Reputation: 15

Python: Reading and obtaining certain parts of a text file

I have a text file that has coordinates in a format of [x1, y1, x2, y2]. How would I be able to obtain just the y1 and y2 coordinates?

Example:

[23, 45, 90, 79]

Obtain 45 and 79

Upvotes: 1

Views: 245

Answers (4)

Roshin Raphel
Roshin Raphel

Reputation: 2709

If your data is a string like s in the given code, Use the strip functions to remove [,] and use the split function, otherwise convert the list, s = [23, 45, 90, 79] into an string by s = str(s):

s = '[23, 45, 90, 79]'
s = s.strip('[').strip(']').split(',')
#Now getting y1 and y2 :
y1 = int(s[1])                # You can use the float() function if needed
y2 = int(s[3])

Upvotes: 0

Osadhi Virochana
Osadhi Virochana

Reputation: 1302

x = [23, 45, 90, 79]

x[1] will be 45 and x[3] will be 79. So you can print them as print(x[1],x[3]).The output will be 45 79

x = [[23, 45, 90, 79],[191, 64, 243, 93],[437, 76, 514, 127]]
for i in range(len(x)):
    print(x[i][1],x[i][3])

will print:

45 79
64 93
76 127

Upvotes: 0

Ronald
Ronald

Reputation: 3335

This will do:

import re

with open('text.txt', 'r') as f:
    for line in f.readlines():
        x, y = re.findall(r'\d+.*?(\d+).*?\d+.*?(\d+)', line)[0] 
        print(x,y)

Upvotes: 1

Jonas
Jonas

Reputation: 1769

If the coordinates always remain at the same position you could use:

array = [23,45,90,79]
y1_y2 = [array[1], array[3]]

Upvotes: 0

Related Questions