Python中按文本列表中的值过滤

Python中按文本列表中的值过滤,python,list,python-3.x,loops,text,Python,List,Python 3.x,Loops,Text,我编写了一个Python脚本,试图过滤一些文本文件并将它们与另一个文本文件进行比较,但是我正在努力找到解决方案 below | 1 above | 2 above | 3 above | 4 above | 5 below | 6 below | 7 below | 8 below | 9 below | 10 below | 11 below | 12 above | 13 below | 14 below | 15 below | 16 below | 17

我编写了一个Python脚本,试图过滤一些文本文件并将它们与另一个文本文件进行比较,但是我正在努力找到解决方案

below | 1

above | 2

above | 3

above | 4

above | 5

below | 6

below | 7

below | 8

below | 9

below | 10

below | 11

below | 12

above | 13

below | 14

below | 15

below | 16

below | 17

below | 18

below | 19

below | 20

below | 21

...
我有这个文件列出了视频帧,以及它们是否高于或低于定义的阈值

此外,我有一个“高于”阈值帧的列表,每个帧都有一个用户定义的标记值(x、y或z)。不幸的是,此列表中的数字与帧号上方或下方的初始数字不对应,而是一个编号列表

y | 1
x | 2
x | 3
y | 4
z | 5
z | 6
y | 7
z | 8
y | 9
y | 10
x | 11
x | 12
y | 13
x | 14
x | 15
x | 16
x | 17
x | 18
y | 19
x | 20
z | 21
我想将这两种方法结合起来,以使上述帧的x、y或z值替换另一个脚本中的“over”标记,如下所示:

below | 1

y | 2

x | 3

x | 4

y | 5

below | 6

below | 7

below | 8

below | 9

below | 10

below | 11

below | 12

z | 13

below | 14

below | 15

below | 16

below | 17

below | 18

below | 19

below | 20

below | 21
然而,我无法理解如何通过迭代列表来实现这一点。我应该将值存储在字典中并对其进行迭代吗?任何帮助都将不胜感激。我尝试过使用一些for循环和open语句来尝试它,但我不知道如何迭代它:

 with open((selectedvideostring + 'combinedfiles.txt'), 'w') as combinedfile:
    with open((selectedvideostring + 'aboveorbelow.txt'), 'r') as aboveorbelowfile:
        for line in aboveorbelowfile:
            if 'above' in line:
                with open((selectedvideostring + 'xyzfile.txt'), 'r') as xyzfile:
                    for line in xyzfile:
                        if 'x' in line:
                            combinedfile.write("x" + '|' + str(int(cap.get(1))))

                        elif 'y' in line:
                            combinedfile.write("y" + '|' + str(int(cap.get(1))))

                        if 'z' in line:
                            combinedfile.write("z" + '|' + str(int(cap.get(1))))

            elif 'below' in line:
                combinedfile.write("below" + '|' + str(int(cap.get(1))))

谢谢

不应在外部的“上下文件”循环中打开和迭代xyz文件,而应同时打开这两个文件。文件是迭代器,因此您可以使用
for
循环来迭代上面或下面文件中的行,并在遇到“上面”条目时使用仅从xyz文件中获取下一行


(使用
print
以简化测试,但当然输出文件也可以使用同样的方法。)

您已经尝试了什么?请将这些文件的内容粘贴到您的问题中,这样我们就不必为了测试可能的解决方案而重新键入所有这些内容。我们现在就这样做,抱歉!对,粘贴的内容,和垃圾代码我到目前为止!谢谢你的帮助!一个小问题,在我的程序中实现该代码,我得到一个错误,读取'StopIteration',将错误抛出到
d,=next(xyz).split(“|”)
@KittenMittons在这种情况下,第二个文件中没有足够的
xyz
值。如果存在可用的默认值,您可以使用带有默认值的
next
,例如
next(xyz,“UNKNOWN | 0”).split(“|”)
。非常感谢-这停止了StopIteration问题-当我使用上述打印语句时,它会完全按照我的要求输出,但是当我尝试将这些行写入新的输出文件时,它完成时没有错误,但没有文件存在-我现在将添加我在原始问题中作为编辑使用的代码,我一定是做错了什么不要紧,是我没有保存正确的文件路径-我已经对其进行了排序,非常感谢您的帮助!!
with open("aboveorbelow.txt") as aob, open("xyzfile.txt") as xyz:
    for line in aob:
        if line.startswith("above"):
            ab, c = line.split(" | ")
            d, _ = next(xyz).split(" | ")
            print(" | ".join((d, c)))
        elif line.startswith("below"):
            print(line)