与python匹配后如何打印行?

时间:2019-06-20 15:08:59

标签: python file

我有一个文件,其中有几行(我只显示其中两行):

UniRef90_A0A0K2VG56 UniRef90_A0A0P5UY87 
UniRef90_A0A095VQ09 UniRef90_A0A0C1UI80 UniRef90_A0A1M4ZSK2

和另一个文件(我只显示文件的某些行):

>UniRef90_A0A095VQ09 - Cluster: LOW QUALITY PROTEIN: titin
MTTKAPTFTQPLQSVVALEGSAATFEAHISGSPVPEVSWYRDGQVLSAATLPGVQISFSD
GRAKLMIPAVAAGHSGRYTLQATNGSGQATSTAELLVTAETAPPNFSQRLQSTTARQGSQ
VRLDVRVTGIPTPVVKFYRDRAEIQSSPDFQILQEGDLYSLIIAEAYPEDSGTYSVNATN
>UniRef90_A0A0K2VG56 - Cluster: titin isoform X29
MATQAPTFTQPLQSVVVLEGSTATFEAHISGFPVPEVSWFRDGQVISTSTLPGVQISFSD
GRAKLMIPAVTKANSGRYSLRATNGSGQATSTAELLVKAETAPPNFVQRLQSMTVRQGSQ
VRLQVRVTGIPTPVVKFYRDGAEIQSSLDFQISQEGELYSLLIVEAYPEDSGTYSVNATN
SVGRATSTAELLVQGEEVVPAKKTKTIVSTAQISKSRETRIEKKIEAHFDARSIATVEMV
IDGAAGQELPHKTPPRIPLKPKSRSPTPPSIAAKAQLARQQSPSPIRHSPSPVRHVRAPT
>UniRef90_A0A0C1UI80 - Cluster: LOW QUALITY PROTEIN: lafev
GRAKLMIPAVTKANSGRYSLRATNGSGQATSTAELLVKAETAPPNFVQRLQSMTVRQGSQ
VRLQVRVTGIPTPVVKFYRDGAEIQSSLDFQISQEGLARQQSPSPIRHSPSPVRHVRAPT
>UniRef90_A0A0P5UY87 - Cluster: titin isoform X4
VRLQVRVTGIPTPVVKFYRDGAEIQSSLDFQISQEGELYSLLIVEAYPEDSGTYSVNATN
SVGRATSTAELLVQGEEVVPAKKTKTIVSTAQISKSRETRIEKKIEAHFDARSIATVEMV
GRAKLMIPAVAAGHSGRYTLQATNGSGQATSTAELLVTAETAPPNFSQRLQSTTARQGSQ
>UniRef90_A0A1M4ZSK2  - Cluster: titin isoform X54
SVGRATSTAELLVQGEEVVPAKKTKTIVSTSTAELLVTAETAPPNFSQRLQSTTARQGSQ
SVGRATSTAELLVQGEEVVPAKKTKTIVSTAQISKSRETRIEKKIEAHFDARSIATVEMV
IDGAAGQELPHKTPPRIPLKPKSRSPTPPSIAAKAQLARQQSPSPIRHSPSPVRHVRAPT

对于第一个文件的每一行,我需要将Uniref90_XXXXXX的ID与第二个文件的Uniref90_XXXXXX的ID进行匹配。匹配完成后,我需要将序列(字母... TNGSGQATS .... =序列)恢复为相应的ID。

例如,在第一个文件的第一行中有2个Uniref90_XXXXX ID,我想得到这样的输出:

>UniRef90_A0A0K2VG56 - Cluster: titin isoform X29
MATQAPTFTQPLQSVVVLEGSTATFEAHISGFPVPEVSWFRDGQVISTSTLPGVQISFSD
GRAKLMIPAVTKANSGRYSLRATNGSGQATSTAELLVKAETAPPNFVQRLQSMTVRQGSQ
VRLQVRVTGIPTPVVKFYRDGAEIQSSLDFQISQEGELYSLLIVEAYPEDSGTYSVNATN
SVGRATSTAELLVQGEEVVPAKKTKTIVSTAQISKSRETRIEKKIEAHFDARSIATVEMV
IDGAAGQELPHKTPPRIPLKPKSRSPTPPSIAAKAQLARQQSPSPIRHSPSPVRHVRAPT   ##first ID of the first line
>UniRef90_A0A0P5UY87 - Cluster: titin isoform X4
VRLQVRVTGIPTPVVKFYRDGAEIQSSLDFQISQEGELYSLLIVEAYPEDSGTYSVNATN   
SVGRATSTAELLVQGEEVVPAKKTKTIVSTAQISKSRETRIEKKIEAHFDARSIATVEMV
GRAKLMIPAVAAGHSGRYTLQATNGSGQATSTAELLVTAETAPPNFSQRLQSTTARQGSQ   ##second ID of the first line

我需要对我的第一个文件的每一行进行该操作。

1 个答案:

答案 0 :(得分:1)

因此,您似乎需要根据第一个文件中的Uniref90_XXXXXX顺序对其进行排序。

此处UniRef_ids.txt是您的第一个文件,UniRef_data.txt是您的第二个文件,而UniRef_data_ordered.txt是输出文件。

我注意到每个Uniref90_XXXXXX似乎都以>开头,并以可变的行数继续,直到下一个>或文件结尾为止。 / p>

我只处理了一个例外:如果Uniref90_XXXXXX出现在您的第一个文件中,而不是您的第二个文件。它只会向您的控制台(而不是您的文件)显示警告。

如果其余文件的格式不同,则可能无法正常工作。同样,如果您的文件为数GB,则我的方法可能不合适,因为我将第二个文件的全部内容读入内存。

# We first go through the second file, get all the Uniref90_XXXXXX IDs, and 
# put their sequences (including the Uniref90_XXXXXX header line) into a dict.
# A sequence can be accessed like so: uniref_dict["UniRef90_A0A0K2VG56"]
with open("UniRef_data.txt", "rt") as f:
    data = f.read()

uniref_dict = {}
for uniref in [f">{chunk.rstrip()}" for chunk in data.split(">")]:
    uniref_id = uniref[1:uniref.find(" ")]
    uniref_dict[uniref_id] = uniref

# Then we go through the first file, line by line, id by id, and write to 
# a new file the corresponding sequence (again, including the Uniref90_XXXXXX 
# header line, as per your output) and append the Uniref90_XXXXXX at the end.
with open("UniRef_ids.txt", "rt") as fin:
    with open("UniRef_data_ordered.txt", "wt") as fout:
        for line in fin:
            line = line.rstrip()
            uniref_ids = line.split(" ")
            for uniref_id in uniref_ids:
                try:
                    fout.write("{} ##{}\n".format(uniref_dict[uniref_id], uniref_id))
                except KeyError as e:
                    print(f"uniref_id '{uniref_id}' found in id file but not data file. Continuing...")

UniRef_data_ordered.txt:

>UniRef90_A0A0K2VG56 - Cluster: titin isoform X29
MATQAPTFTQPLQSVVVLEGSTATFEAHISGFPVPEVSWFRDGQVISTSTLPGVQISFSD
GRAKLMIPAVTKANSGRYSLRATNGSGQATSTAELLVKAETAPPNFVQRLQSMTVRQGSQ
VRLQVRVTGIPTPVVKFYRDGAEIQSSLDFQISQEGELYSLLIVEAYPEDSGTYSVNATN
SVGRATSTAELLVQGEEVVPAKKTKTIVSTAQISKSRETRIEKKIEAHFDARSIATVEMV
IDGAAGQELPHKTPPRIPLKPKSRSPTPPSIAAKAQLARQQSPSPIRHSPSPVRHVRAPT ##UniRef90_A0A0K2VG56
>UniRef90_A0A0P5UY87 - Cluster: titin isoform X4
VRLQVRVTGIPTPVVKFYRDGAEIQSSLDFQISQEGELYSLLIVEAYPEDSGTYSVNATN
SVGRATSTAELLVQGEEVVPAKKTKTIVSTAQISKSRETRIEKKIEAHFDARSIATVEMV
GRAKLMIPAVAAGHSGRYTLQATNGSGQATSTAELLVTAETAPPNFSQRLQSTTARQGSQ ##UniRef90_A0A0P5UY87
>UniRef90_A0A095VQ09 - Cluster: LOW QUALITY PROTEIN: titin
MTTKAPTFTQPLQSVVALEGSAATFEAHISGSPVPEVSWYRDGQVLSAATLPGVQISFSD
GRAKLMIPAVAAGHSGRYTLQATNGSGQATSTAELLVTAETAPPNFSQRLQSTTARQGSQ
VRLDVRVTGIPTPVVKFYRDRAEIQSSPDFQILQEGDLYSLIIAEAYPEDSGTYSVNATN ##UniRef90_A0A095VQ09
>UniRef90_A0A0C1UI80 - Cluster: LOW QUALITY PROTEIN: lafev
GRAKLMIPAVTKANSGRYSLRATNGSGQATSTAELLVKAETAPPNFVQRLQSMTVRQGSQ
VRLQVRVTGIPTPVVKFYRDGAEIQSSLDFQISQEGLARQQSPSPIRHSPSPVRHVRAPT ##UniRef90_A0A0C1UI80
>UniRef90_A0A1M4ZSK2  - Cluster: titin isoform X54
SVGRATSTAELLVQGEEVVPAKKTKTIVSTSTAELLVTAETAPPNFSQRLQSTTARQGSQ
SVGRATSTAELLVQGEEVVPAKKTKTIVSTAQISKSRETRIEKKIEAHFDARSIATVEMV
IDGAAGQELPHKTPPRIPLKPKSRSPTPPSIAAKAQLARQQSPSPIRHSPSPVRHVRAPT ##UniRef90_A0A1M4ZSK2


  

是否可以为每次迭代创建单独的文件   环?我的意思是,对于第一个文件的每一行,我想创建一个   ID和相应序列的文件?

是的,那是可能的。我们只需要打开输出文件并在for循环内编写代码,该循环遍历第一个文件中的行,并为每个文件指定唯一的名称。

# We first go through the second file, get all the Uniref90_XXXXXX IDs, and 
# put their sequences (including the Uniref90_XXXXXX header line) into a dict.
# A sequence can be accessed like so: uniref_dict["UniRef90_A0A0K2VG56"]
with open("UniRef_data.txt", "rt") as f:
    data = f.read()

uniref_dict = {}
for uniref in [f">{chunk.rstrip()}" for chunk in data.split(">")]:
    uniref_id = uniref[1:uniref.find(" ")]
    uniref_dict[uniref_id] = uniref

# Then we go through the first file, line by line, and write to a new  
# file the ids and their corresponding sequences (again, including the 
# Uniref90_XXXXXX header line, as per your output)
with open("UniRef_ids.txt", "rt") as fin:
    # Each iteration of this for loop is a new line of Uniref90_XXXXXX ids,
    # so we've moved the file writing code inside of this loop.
    # enumerate gives us a counter - i - that starts at 1, and increments by 1
    # after each iteration. We use this to give each file a unique name.
    for i, line in enumerate(fin, start=1):
        line = line.rstrip()
        uniref_ids = line.split(" ")
        with open(f"UniRef_data_by_id_row_{i:03}.txt", "wt") as fout:
            for uniref_id in uniref_ids:
                try:
                    fout.write(uniref_dict[uniref_id] + "\n")
                except KeyError as e:
                    print(f"uniref_id '{uniref_id}' found in id file but not data file. Continuing...")

顺便说一下,这是生成我们文件名的代码:

f"UniRef_data_by_id_row_{i:03}.txt"

f前缀告诉Python它是f-string。它评估{}中的内容并返回一个字符串。 :之前是,之后是格式说明符。在这种情况下,我的格式说明符将0-pads i的宽度指定为3,给我这样的文件名:

UniRef_data_by_id_row_001.txt
UniRef_data_by_id_row_999.txt

这样,在文件管理器中对文件进行排序非常容易。

您可以使用不同的名称命名文件。例如,如果您不想使用下划线,并且想用空格而不是0来填充数字:

f"UniRef Data Ordered by ID - Row {i: >4}.txt"
UniRef Data Ordered by ID - Row    1.txt
UniRef Data Ordered by ID - Row 9999.txt