繁体   English   中英

如何删除 Python 循环中的前一次迭代?

[英]How to delete a previous iteration in a Python loop?

在此先感谢您的帮助。

我有一个由许多书组成的大型文本文档。 所有的书都有“运行标题”,我注意到它们出现在页码行之前。 页码有 1 到 4 位数字。 页码换行。

我想遍历文件并让 Python 在到达以页码开头的行时删除上一次迭代。

谢谢

贝内特

我的示例代码是:

import re
f=open("corpus.txt", "r+", "a")
for line in f:
    line = line.rstrip()
    if re.search('^[0-9]*?', line):
        #delete previous line

在此先感谢您的帮助。

我有一个由许多书籍组成的大型文本文档。 所有书籍都有“运行标题”,我注意到它们出现在页码行之前。 页码有 1 到 4 位数字。 页码在新行上。

我想遍历文件并使 Python 在到达以页码开头的行时删除上一次迭代。

谢谢

贝内特

我的示例代码是:

import re
f=open("corpus.txt", "r+", "a")
for line in f:
    line = line.rstrip()
    if re.search('^[0-9]*?', line):
        #delete previous line

代码:

file = open(r"C:\Users\Asus\Desktop\sample.txt").read().splitlines()
output = open(r"C:\Users\Asus\Desktop\output.txt",'w')
for index, line in enumerate(file):
    try:
        if file[index+1].strip().isdigit() == False and file[index].strip().isdigit() == False:
            output.write(file[index])
            output.write('\n')
    except:    
        output.write(file[index])  #printing last line
        output.write('\n')
output.close()

输入:

wearing sandals, a cock that crows, a cloak
to dissect, a sponge, some vinegar and one
man to hammer the nails home.
56

Or you can take a length of steel,
castle to hold your banquet in.
77

wearing sandals, a cock that crows, a cloak
to dissect, a sponge, some vinegar and one

输出:

wearing sandals, a cock that crows, a cloak
to dissect, a sponge, some vinegar and one

Or you can take a length of steel,

wearing sandals, a cock that crows, a cloak
to dissect, a sponge, some vinegar and one

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM