Как я могу создать dict из извлечения данных из файла .txt? - PullRequest
0 голосов
/ 20 июня 2019

Я настраиваю алгоритм, который получает значения из txt-файла в списки.

Например, txt-файл может быть:

points
 -1 -4
 5 6
 7 8
NextPoints 1
points;
points
 -2 -7
NextFile 1

На данный момент у меня естьсоздал dict:

number_of_points = text.count('points\n')
for i in range(number_of_points):
   dict=['list%s' % i] = list_points

Дело в том, что этот dict возвращает:

{list1 : [-1, -4, 5, 6, 7, 8], list2 : [-1, -4, 5, 6, 7, 8, -2, -7]}

, но я хочу это:

{list1 : [-1, -4, 5, 6, 7, 8], list2 : [-2, -7]}

Цель состоит в том, чтобы принять врассмотреть все «точки» в файле и поместить каждый из них в список.Основная часть моего текстового файла содержит только 1 очко.

Обновление

while line:
  if line.lstrip().startswith('points') and not (line.rstrip().endswith(';')):
     if line.startswith(' '):
         pointsDefect['list{}'.format(c)] = next(f).strip().split()
         c += 1

Ответы [ 2 ]

1 голос
/ 20 июня 2019

Это один из подходов.

Демо:

result = {}
c = 1
with open(filename) as infile:
    for line in infile:
        if line.strip() == "points":    #If line == "points" Get data from next line.
            line = next(infile)
            temp = []
            while not line.strip().startswith("Next"):
                temp.extend(line.strip().split())
                line = next(infile)
            result['list{}'.format(c)] = list(map(int, temp))
            c += 1
print(result)

Выход:

{'list1': [-1, -4, 5, 6, 7, 8], 'list2': [-2, -7]}
0 голосов
/ 20 июня 2019

Есть более простые решения, почему бы не что-то вроде этого:

import re

result, current = [], []
with open("/path/to/file", "r") as f:
    for line in f:
        if current and line[:6] == "points":
            result.append(current)
            current = []
        if re.match(r"(-?\d+ ?)+", line.strip()):
            current.extend([int(s) for s in line.split()])
result.append(current)

print(result)  # >> [[-1, -4, 5, 6, 7, 8], [-2, -7]]

# if you really need the {list1': xxx} pattern:
result = {f'list{i+1}': l for i, l in enumerate(result)}

print(result) # >> {'list1': [-1, -4, 5, 6, 7, 8], 'list2': [-2, -7]}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...