首页 > 解决方案 > 使用 Python 字典计算 txt 文件中的项目

问题描述

我有以下 txt 文件(只给出了一个片段)

     ## DISTANCE : Shortest distance from variant to transcript
## a lot of comments here
    ## STRAND : Strand of the feature (1/-1)
    ## FLAGS : Transcript quality flags
    #Uploaded_variation     Location        Allele  Gene    Feature Feature_type    Consequence     cDNA_position   CDS_position    Protein_position        Amino_acids     Codons  Existing_variation      Extra
    chr1_69270_A/G  chr1:69270      G       ENSG00000186092 ENST00000335137 Transcript      upstream_gene_variant      216     180     60      S       tcA/tcG -       IMPACT=LOW;STRAND=1
    chr1_69270_A/G  chr1:69270      G       ENSG00000186092 ENST00000641515 Transcript      intron_variant      303     243     81      S       tcA/tcG -       IMPACT=LOW;STRAND=1
    chr1_69511_A/G  chr1:69511      G       ENSG00000186092 ENST00000335137 Transcript      upstream_gene_variant        457     421     141     T/A     Aca/Gca -       IMPACT=MODERATE;STRAND=1

有许多未知的各种ENSG编号,例如ENSG00000187583等。每个ENSG字符串中的整数计数为11。

我必须计算每个基因(ENSGxxx)包含多少个 intron_variant 和 upstream_gene_variant。并将其输出到 csv 文件。

我为此目的使用字典。我试图编写这段代码,但不确定语法是否正确。逻辑应该是:如果这11个数字不在字典中,则应添加值1。如果它们已经在字典中,则应将值更改为x + 1。我目前有此代码,但我不是真正的Python程序员,不确定语法是否正确。

    with open(file, 'rt') as f:
        data = f.readlines()
        Count = 0
        d = {}
        for line in data:
            if line[0] == "#":
                output.write(line)
            if line.__contains__('ENSG'): 
                d[line.split('ENSG')[1][0:11]]=1
                if 1 in d:
                    d=1
                else:
                    Count += 1

有什么建议么?

谢谢!

标签: pythondictionarycountbioinformaticscontains

解决方案


你可以试试这个:

from collections import Counter

with open('data.txt') as fp:
    ensg = []
    for line in fp:
        idx = line.find('ENSG')
        if not line.startswith('#') and idx != -1:
            ensg.append(line[idx+4:idx+15])
count = Counter(ensg)
>>> count
Counter({'00000187961': 2, '00000187583': 2})

更新

我需要知道有多少 ENG 包含“intron_variant”和“upstream_gene_variant”

使用正则表达式提取所需的模式:

from collections import Counter
import re

PAT_ENSG = r'ENSG(?P<ensg>\d{11})'
PAT_VARIANT = r'(?P<variant>intron_variant|upstream_gene_variant)'

PATTERN = re.compile(fr'{PAT_ENSG}.*\b{PAT_VARIANT}\b')

with open('data.txt') as fp:
    ensg = []
    for line in fp:
        sre = PATTERN.search(line)
        if not line.startswith('#') and sre:
            ensg.append(sre.groups())
    count = Counter(ensg)

输出:

>>> count
Counter({('00000186092', 'upstream_gene_variant'): 2,
         ('00000186092', 'intron_variant'): 1})

推荐阅读