import argparse

parsed = 0


def make_parser():
    parser = argparse.ArgumentParser()
    parser.add_argument('dat_file', metavar="FILE", help="swissprot dat file")
    parser.add_argument('taxon_file', metavar="FILE", help="file with tax id to filter"
            " (one per line)")
    parser.add_argument('output_file', metavar="FILE", help="output (filtered) file")
    return parser.parse_args()


def parse_dat_file(filename: str, banned_tax_file: str):
    global parsed
    banned_taxa = set([x.strip() for x in open(banned_tax_file)])
    found_taxa = []
    lines = []
    for line in open(filename):
        output = False 
        if line.strip() == "//":
            output = True
            parsed += 1
        elif "NCBI_TaxID" in line:
            found_taxon = line.split(";")[0].split("=")[1]
            found_taxa.append(found_taxon)
        lines.append(line)
        if output:
            if all([found_tax not in banned_taxa for found_tax in found_taxa]):
                yield lines
            lines = []
            found_taxa = []


def main():
    args = make_parser()
    with open(args.output_file, "w") as out:
        for written, entries in enumerate(parse_dat_file(args.dat_file, args.taxon_file)):
            out.write("".join(entries))
        print(f"Written {written + 1:,} entries out of {parsed:,} ({(written + 1)*100/parsed:.2f}%).")


if __name__ == "__main__":
    main()

import argparse

parsed = 0


def make_parser():
    parser = argparse.ArgumentParser()
    parser.add_argument('dat_file', metavar="FILE", help="swissprot dat file")
    parser.add_argument('taxon_file', metavar="FILE", help="file with tax id to filter"
            " (one per line)")
    parser.add_argument('output_file', metavar="FILE", help="output (filtered) file")
    return parser.parse_args()


def parse_dat_file(filename: str, banned_tax_file: str):
    global parsed
    banned_taxa = set([x.strip() for x in open(banned_tax_file)])
    found_taxa = []
    lines = []
    for line in open(filename):
        output = False 
        if line.strip() == "//":
            output = True
            parsed += 1
        elif "NCBI_TaxID" in line:
            found_taxon = line.split(";")[0].split("=")[1]
            found_taxa.append(found_taxon)
        lines.append(line)
        if output:
            if all([found_tax not in banned_taxa for found_tax in found_taxa]):
                yield lines
            lines = []
            found_taxa = []


def main():
    args = make_parser()
    with open(args.output_file, "w") as out:
        for written, entries in enumerate(parse_dat_file(args.dat_file, args.taxon_file)):
            out.write("".join(entries))
        print(f"Written {written + 1:,} entries out of {parsed:,} ({(written + 1)*100/parsed:.2f}%).")


if __name__ == "__main__":
    main()
