如何从提取.txt文件的数据中创建字典?

时间:2019-06-20 12:10:38

标签: python-3.x list dictionary

我正在设置一种算法,该算法将从txt文件中获取值到列表中。

例如,txt文件可以是:

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

目前,我已经创建了一个字典:

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

事实是该字典返回:

{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 个答案:

答案 0 :(得分:1)

这是一种方法。

演示:

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]}

答案 1 :(得分:0)

有更简单的解决方案,为什么不这样呢?

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]}