0

我有一个文本文件:

>E8|E2|E9D
Football is a good game
Its good for health
you can play it every day
>E8|E2|E10D
Sequence unavailable
>E8|E2|EKB
Cricket
>E87|E77|E10D
Sequence unavailable
>E27|E97|E10D
Sequence unavailable
>E8|E2|E9D
Sequence unavailable

我编写了以下代码用于Sequence unavailable从该文件中检测并删除它:

with open('input.txt') as f1, open('output.txt', 'w') as f2,\
                                                  open('temp_file','w') as f3:
    lines = []       # store lines between two `>` in this list
    for line in f1:
        if line.startswith('>'):
            if lines:
                f3.writelines(lines)
                lines = [line]
            else:
                lines.append(line)
        elif line.rstrip('\n') == 'Sequence unavailable':
            f2.writelines(lines + [line])
            lines = []
        else:
            lines.append(line)

    f3.writelines(lines)

os.remove('input.txt')
os.rename('temp_file', 'input.txt')

但我真正想要的是删除给定问题的所有可用序列(行的最后一列>)。

例如,即使后面有行E9D,如果有另一个没有条目的E9D条目 ,Sequence unavailable则应将其写入输出文件:

输入.txt

>E8|E2|E9D
Football is a good game
Its good for health
you can play it every day
>E8|E2|E10D
Sequence unavailable
>E8|E2|EKB
Cricket
>E87|E77|E10D
Sequence unavailable
>E27|E97|E10D
Sequence unavailable
>E8|E2|E9D
Sequence unavailable

输出.txt

>E8|E2|EKB
Cricket

这里只有EKB问题有条目。

4

2 回答 2

1
def get_name(line):
    return line[1:].rsplit('|', 1)[-1].strip()

with open('input.txt') as f, open('output.txt', 'w') as fout:
    name = ''

    # Phase 1: Find unavailable sequence
    unavailable = set()
    for line in f:
        if line.startswith('>'):
            name = get_name(line)
        else:
            if 'Sequence unavailable' in line:
                unavailable.add(name)

    # Phase 2: Filter avilable sequence
    f.seek(0)
    keep = False
    for line in f:
        if line.startswith('>'):
            name = get_name(line)
            keep = name not in unavailable
        if keep:
            fout.write(line)
于 2013-07-27T09:15:46.120 回答
0

您可以采用另一种更简单的方法。您可以将其替换为“”,而不是删除该行

import fileinput
import sys

f=open('input.txt')
line = f.readline()
f.close()
words = line.split()
for word in words:
    line = line.replace("Sequence unavailable","")
    line = line.replace("\n","")

我没有执行这段代码,但我认为逻辑是正确的。请注意,您必须使用第二次替换,因为每次都会有一个新行。

于 2013-07-27T09:49:04.860 回答