我正在尝试解析具有一致格式的文件:标题和按间距分割的几行文本。 我想当一行有一个值时启动一个新的字典键,将以下行读入列表列表中,每个列表都是拆分词。 我首先尝试使用this尝试让程序识别新标记并使用索引计数器设置新 key 。 然后我最初使用 this相应地分割线。
这是我的代码当前的样子:
import sys
def openfile(file):
frames = {}
index = 0
with open(file, 'r') as f:
for line in f:
if line.strip() == '5310':
index +=1
else:
newline = line
print newline
frames[index] = []
frames[index].append([newline.split()])
print frames
openfile(sys.argv[1])
索引将正确计数,并且“打印换行符”正在打印我想要的所有行,但最终打印的字典是一个嵌套列表:
{1:[['last', 'line', 'of', 'input', 'file']]}
我想要的是:
{1:[[line1],[line2] ...], 2:[[nextline], [nextline] ...], ... , key n : [[line], [line]....[lastline]]}
我也尝试过:
def openfile(file):
frames = {}
index = 0
with open(file) as f:
for line in f:
if str(line.strip()) == '5310':
index += 1
else:
frames[index] = []
frames[index].append([line.split()])
return frames
这也行不通。 这给我留下了两个问题: 1:为什么我当前的代码会打印但不会 append 我想要的行? 2.我还能尝试什么来让它发挥作用?
编辑 谢谢!我设法让它发挥作用。 如果有人遇到类似的问题,这是我的有效代码:
import sys
def openfile(file):
frames = {}
index = 0
with open(file, 'r') as f:
for line in f:
if line.strip() == '5310':
index +=1
frames[index] = []
else:
newline = line
print newline
frames[index].append([newline.split()])
print frames
openfile(sys.argv[1])
最佳答案
你的问题很明显......一旦你看到问题:-)
frames[index] = []
frames[index].append([newline.split()])
每次循环时,您都会清除之前的进度,并从一个新的空列表开始。因此,只有最后一次迭代的结果位于帧
中。
初始化代码只需在进入循环之前完成一次。
with open(file) as f:
frames[index] = []
for line in f:
...或其他适合您应用程序的点。
关于Python将文件解析为列表列表字典: for loop is only appending last line,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51069334/