Python 在迭代过程中删除行的范围

Python 在迭代过程中删除行的范围,python,linux,Python,Linux,我有一个kml数据文件(~160000行)。在Python脚本中,我需要在标记中搜索关键字“Unmatched”,如果找到,则删除从到与该命名条目关联的所有内容 我在这里尝试过论坛,有一次,效果不错,但当我需要在同一个文件中执行数百次此操作时,我没有成功。有34条线路需要拆除。”prev'获取删除需要开始的起始行,“end”是它停止的位置。。。因此,我需要删除[prev:end],然后写入这些更改 #!/usr/bin/python lookup = 'Unmatched ' with open

我有一个kml数据文件(~160000行)。在Python脚本中,我需要在
标记中搜索关键字“Unmatched”,如果找到,则删除从
与该命名条目关联的所有内容

我在这里尝试过论坛,有一次,效果不错,但当我需要在同一个文件中执行数百次此操作时,我没有成功。有34条线路需要拆除。”prev'获取删除需要开始的起始行,“end”是它停止的位置。。。因此,我需要删除[prev:end],然后写入这些更改

#!/usr/bin/python
lookup = 'Unmatched '
with open('doc.kml') as myFile:
    for num, line in enumerate(myFile, 1):
        if lookup in line:
            print 'Found in Line:', num
            prev = num-1
            print 'Placemark Starts at line:', prev
            end = prev+33
            print '/Placemark Ends at line:', end

我会忘记行号。关注这一行的内容

  • 将行存储在另一行列表中
  • 找到开始模式后,使用
    next
  • “删除前一行”问题可以通过弹出存储在输出行列表中的最后一行来解决
像这样:

lookup = 'Unmatched '
filtered = []   # output list of lines
with open('doc.kml') as myFile:
    for line in myFile:
        if lookup in line:
            filtered.pop()  # drop the line we just added
            for _ in range(34): # not sure of how many, you'll see
                next(myFile,None)  # drop a line
        else:
           filtered.append(line)

# in the end write back filtered file if needed (one could write directly instead of using a list to append to)
with open('newdoc.kml') as f:
    f.writelines(filtered)

我会忘记行号。关注这一行的内容

  • 将行存储在另一行列表中
  • 找到开始模式后,使用
    next
  • “删除前一行”问题可以通过弹出存储在输出行列表中的最后一行来解决
像这样:

lookup = 'Unmatched '
filtered = []   # output list of lines
with open('doc.kml') as myFile:
    for line in myFile:
        if lookup in line:
            filtered.pop()  # drop the line we just added
            for _ in range(34): # not sure of how many, you'll see
                next(myFile,None)  # drop a line
        else:
           filtered.append(line)

# in the end write back filtered file if needed (one could write directly instead of using a list to append to)
with open('newdoc.kml') as f:
    f.writelines(filtered)

一种可能的方法是将行写入另一个列表,并使用
next
33/34次手动迭代,以便在pattern Found时跳过行。您可以显示一个小样本数据吗?一种可能的方法是将行写入另一个列表,并使用
next
33/34次手动迭代,以便在pattern Found时跳过行显示一小部分数据?谢谢Jean。我认为这种方法效果更好。当我找到关键词时,我需要返回一行,删除那一行和接下来的33行。如果我在关键字行开始删除,我将退出。谢谢你。我认为这种方法效果更好。当我找到关键词时,我需要返回一行,删除那一行和接下来的33行。如果我在关键字行开始删除,我将退出。