Ecem Şimşek
Ecem Şimşek

Reputation: 21

read by white space

I have a .txt file with the following single line

(1,65,b) (2,50,r) (3,80,b) (4,10,b) (5,60,b) (6,70,r) (8,5,r) (11,62,r)

where the first element of the tuple is the position, second is value and the third one is color. For example for the first tuple: position = 1, value = 65 and color is b.

How can I read this file in a way that I can create list of positions, values, and colors.

Upvotes: 1

Views: 84

Answers (3)

Diwakar SHARMA
Diwakar SHARMA

Reputation: 581

Here is another simple solution using replace .

import os
import time
import sys

output  = "(1,65,b) (2,50,r) (3,80,b) (4,10,b) (5,60,b) (6,70,r) (8,5,r) (11,62,r)"

a = ((((output.replace("(",'')).replace(")",'')).replace(' ',',')).split(','))

e = a[0::3]
f = a[1::3]
g = a[2::3]

print(e,f,g)

Output:
['1', '2', '3', '4', '5', '6', '8', '11'] ['65', '50', '80', '10', '60', '70', '5', '62'] ['b', 'r', 'b', 'b', 'b', 'r', 'r', 'r']

Upvotes: 1

Thaer A
Thaer A

Reputation: 2323

Try this (explanation in code comment):

file = "(1,65,b) (2,50,r) (3,80,b) (4,10,b) (5,60,b) (6,70,r) (8,5,r) (11,62,r)"

positions=[]
values=[]
colors=[]
# assuming that the values are stored in one line in the file, loop through text in file splitting text by space
for item in file.split(" "):
    # split the text in between brackets [text betwen 1 to -1 >[1:-1] by comma
    # append each item to corosponding list
    positions.append(item[1:-1].split(",")[0])
    values.append(item[1:-1].split(",")[1])
    colors.append(item[1:-1].split(",")[2])

print(positions, values, colors)

One line solution:

file = "(1,65,b) (2,50,r) (3,80,b) (4,10,b) (5,60,b) (6,70,r) (8,5,r) (11,62,r)"
p,c,v = [list(map(lambda x:x[1:-1].split(",")[i], file.split(" ") )) for i in range(3)]
print (p,c,v)

Upvotes: 1

Sabito
Sabito

Reputation: 5075

You can you regular expressions for searching the string.

import re

string = open ('text.txt').read()

position = list(map(int,re.findall(f'\(([0-9]+)',string)))
value = list(map(int,re.findall(f',([0-9]+)',string)))
color = list(re.findall(f'([a-z])\)',string))
print(position,value,color)

#output:
[1, 2, 3, 4, 5, 6, 8, 11] [65, 50, 80, 10, 60, 70, 5, 62] ['b', 'r', 'b', 'b', 'b', 'r', 'r', 'r']

Upvotes: 1

Related Questions