在文本fi中查找矩阵

2024-09-27 19:11:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python初学者,我正在尝试从我的数据文件中提取矩阵。此文件包含有关测量参数的信息,例如文本+数字。我想提取放在单词“#UBI:”和“#translation”之间的矩阵。这个文件包含数百个这样的矩阵。所以这是我试图运行的代码-它给了我一些结果,但似乎有一个无限循环-它从不停止:

inF = open("C:/Python27/allgrainmap3.map")

line=inF.readline()

while True:
    inF = open("C:/Python27/allgrainmap3.map")
    outF = open("matrices.txt", "w")
    keepCurrentSet = False
    for line in inF:

        if line.startswith("#translation"):
            keepCurrentSet = False

        if keepCurrentSet:
            outF.write(line)

        if line.startswith("#UBI:"):
            keepCurrentSet = True

    if not line: break

inF.close()
outF.close()

文件块如下所示:

translation 4141 14141
bla bla 
bla bla 
UBI: 1 2 3 4 5 6 7 8 9 # this is the matrix I want 

翻译。。。 在这里,我只需要矩阵e.I.向量的最后一列包含(3 6 9)。你知道吗


Tags: 文件truemapifline矩阵opentranslation
1条回答
网友
1楼 · 发布于 2024-09-27 19:11:53

您正在代码中的两个不同位置打开输入文件,这似乎不是您想要做的。你知道吗

我也看不到while True:的目的,它应该是无限循环的原因。。。你知道吗

我觉得这样行得通

inF = open("C:/Python27/allgrainmap3.map")
outF = open("matrices.txt", "w")
keepCurrentSet = False
for line in inF:

        if line.startswith("#translation"):
            keepCurrentSet = False

        if keepCurrentSet:
            outF.write(line)

        if line.startswith("#UBI:"):
            keepCurrentSet = True

inF.close()
outF.close()

现在,如果只想保留最后一列,则必须在将其写入outfile之前对其进行处理:

 if keepCurrentSet:
   vector = line[9::3]
   outF.write(vector)

这只适用于当前矩阵:如果列数发生变化,则必须计算要保留在切片中的元素。你知道吗

编辑:如果矩阵中有数字而不是单个数字:

line = "UBI: 101 223 33456 40 51 63 75 86 99"
fields = line.split()
vector = fields[3::3]
print(vector)

仅适用于3x3矩阵。你知道吗

相关问题 更多 >

    热门问题