簡體   English   中英

在Python的文本文件中使用變量重復提取兩個定界符之間的文本

[英]Repeatedly extract text between two delimiters with a variable in a text file in Python

我有一個包含我所有感興趣基因的基因列表(gene1,gene2等)。 我現在想分別為每個基因提取自由能數據,以分別處理它。

我的數據集如下所示,其中包含500多個基因的信息:

    ==> data/gene1_free_energy.dat <==
    0                0                0
    1                0                0
    2                0                2.3
    3                0                5.4
    .
    .
    .

    ==> data/gene1_rare_enrichment.dat <==
    7         0.166667         0.939498
    8         0.222222         0.930714
    9         0.0555556        0.998125
    10        0.166667         0.826133
    .
    .
    .

    ==> data/gene2_free_energy.dat <==
    0                0                0
    1                0                0
    2                0                2.3
    3                0                5.4
    .
    .
    .

    ==> data/gene2_rare_enrichment.dat <==
    7         0.166667         0.939498
    8         0.222222         0.930714
    9         0.0555556        0.998125
    10        0.166667         0.826133
    .
    .
    .

現在,要提取兩個定界符之間的數據,我發現此答案非常有用: 在文本文件Python中重復提取兩個定界符之間的一行,但是我不知道如何將基因名稱實現為可變變量。

    import re
    with open(input1) as fp:
    for result in re.findall('==> data/gene1_free_energy.dat <==(.*?)==>  data/gene1_rare_enrichment.dat <==', fp.read(), re.S):
        print (result) #or save this in a dictionary or whatever

這很好地打印出gene1。

我嘗試了以下操作,但是不起作用。

    import re
    for name in gene_list: # this is my list of included genes
        with open(input1) as fp:
        for result in re.findall('==> data/' + name + '_free_energy.dat <==(.*?)==>  data/'+ name +'_rare_enrichment.dat <==', fp.read(), re.S):
            print (result)

有沒有辦法寫這樣的循環? 還是有另一種更聰明的方式來提取我需要的數據?

with open('data.txt') as f:
    RC = False
    D = []
    key = []
    d = []
    for line in f:
        if 'free_energy' in line:
            RC = True
            key.append(line.split('/')[1].split('_')[0])
        if RC:
            if '==>' not in line:
                d.append(line.split())
        if 'rare_enrichment' in line:
            RC = False
            D.append(d)
            d = []



data = {k: a for k, a in zip(key, D)}

output: {'gene1': [['0', '0', '0'],
         ['1', '0', '0'],
         ['2', '0', '2.3'],
         ['3', '0', '5.4']],
         'gene2': [['0', '0', '0'],
         ['1', '0', '0'],
         ['2', '0', '2.3'],
         ['3', '0', '5.4']]}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM