【问题标题】:Find and remove lines in Python and output result在 Python 中查找和删除行并输出结果
【发布时间】:2016-02-20 01:46:21
【问题描述】:

我有一个大文件。我想从中删除一些行。我发现了一些其他类似的问题,但它们不是这样的。该文件如下所示:

A_B 3
Line 1
Line 2
Line 3

C_D 2
Another Line 1
Another line 2

A_B 1
Different line 1

想象一下只有这些行的大文件。首先会有像 A_B、C_D、E_G 等的常量字符串,然后会有像 A_B 3、C_D 4 等的可变数字。然后是行数,例如如果有 A_B 2,那么后面是 2线。如果有 A_B 3 则后面会跟 3 行。我想删除“A_B(数字)”本身和之后的行(数字)。在上面,输出应该是:

C_D 2
Another Line 1
Another line 2

我已经用 Python 编写了脚本,它会打印我不想要的内容:

with open('file.txt') as oldfile:
   for line in oldfile:
         if 'A_B' in line:
             number=line.split()[1]

             num=int(number)
             print
             print line,
             for i in range(num):
                 print next(oldfile),

【问题讨论】:

  • 那么...它打印的是什么
  • 它应该打印除“A_B 2”行和后面的2行之外的所有其他行。

标签: python python-2.7


【解决方案1】:
unwanted_headers=['A_B']
skip_this_many=0

with open('file.txt','r') as oldfile:
    for line in oldfile:
        if not skip_this_many:
            for unwanted_header in unwanted_headers:
                if line.startswith(unwanted_header):
                    skip_this_many=int(line.split()[1])
                else:
                    print line
        else:
            skip_this_many -= 1

【讨论】:

  • 嘿,谢谢。感谢您的快速回答。我也会试试这个。
【解决方案2】:

我不确定我是否理解您的问题,但我认为这样可以解决问题:

f = open("file.txt", "r")
lines = f.readlines()
f.close()

f = open("file.txt", "w")
num = 0
for line in lines:
    if num > 0:
        num = num - 1
    elif 'A_B' in line:
        number = line.split()[1]
        num = int(number)
    else:
        f.write(line)
f.close()

【讨论】:

    【解决方案3】:

    我不知道您为什么要编写一个程序来打印您不想要的所有内容。如果我理解,这将打印您想要的内容:

    with open('file.txt') as oldfile:
        skip = 0
        for line in oldfile:
            if skip > 0:
                skip -= 1
            elif 'A_B' in line:
                number = line.split()[1]
                skip = int(number)
            else:
                print line
    

    【讨论】:

    • 嘿,谢谢。感谢您的快速回答。我也会试试这个。
    【解决方案4】:

    这会打印您试图在测试中获得的打印,不会删除该行。

    MYFILE = '/path/to/longfile.txt'
    
    with open(MYFILE) as oldfile:
    
        line = oldfile.readline()
        while line:
            if line.startswith('A_B'):
               skip_counter = line.split()[1]
               for _ in xrange(int(skip_counter)):
                   oldfile.readline()
            else:
                print line
    
            line = oldfile.readline()
    

    输出:

    C_D 2
    Another Line 1
    Another line 2
    

    【讨论】:

    • 嘿,谢谢。感谢您的快速回答。我也会试试这个。
    猜你喜欢
    • 2023-03-30
    • 1970-01-01
    • 2021-01-26
    • 1970-01-01
    • 2019-01-01
    • 2021-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多