Python 3.x 如何通过提取.txt文件的数据来创建dict?
我正在设置一个算法,将txt文件中的值放入列表中 例如,txt文件可以是: 要点 -1 -4 5 6 7 8 下一点1 点数; 要点 -2 -7 下一个文件1 现在,我已经创建了一个dict:Python 3.x 如何通过提取.txt文件的数据来创建dict?,python-3.x,list,dictionary,Python 3.x,List,Dictionary,我正在设置一个算法,将txt文件中的值放入列表中 例如,txt文件可以是: 要点 -1 -4 5 6 7 8 下一点1 点数; 要点 -2 -7 下一个文件1 现在,我已经创建了一个dict: 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,
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个“点”幻影
更新
这是一种方法
演示:
输出:
有更简单的解决方案,为什么不这样做:
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]}
它返回:{'list4':['NextPoints','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]}
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]}