читать пустым пространством - PullRequest
0 голосов
/ 19 апреля 2020

У меня есть файл .txt со следующей строкой

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

, где первый элемент кортежа - это позиция, второй - значение, а третий - цвет. Например, для первого кортежа: позиция = 1, значение = 65 и цвет b.

Как я могу прочитать этот файл так, чтобы я мог создать список позиций, значений и цветов.

Ответы [ 3 ]

1 голос
/ 19 апреля 2020

Вы можете регулярные выражения для поиска строки.

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']
1 голос
/ 19 апреля 2020

Вот еще одно простое решение с использованием замены.

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']
0 голосов
/ 19 апреля 2020

Попробуйте (пояснение в комментарии к коду):

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)

Решение в одну строку:

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)
...