python - 如何比较一个文件中的多行并输出组合条目

标签 python perl unix awk bioinformatics

我有一个显示四列的文件:

chr开始结束转录

像这样:

chrI    128980  129130  F53G12.5b  
chrI    132280  132430  F53G12.5c.2  
chrI    132280  132430  F53G12.5a  
chrI    132280  132430  F53G12.5b  
chrI    132280  132430  F53G12.5c.1  
chrI    133600  133750  F53G12.5c.2  
chrI    133600  133750  F53G12.5a  
chrI    133600  133750  F53G12.5b  
chrI    133600  133750  F53G12.5c.1  
chrI    136240  136390  F53G12.4  
chrI    139100  139250  F53G12.3  
chrI    163220  163370  F56C11.2a  
chrI    163220  163370  F56C11.2b  
chrI    173900  174050  F56C11.6a  
chrI    173900  174050  F56C11.6b  
chrI    173900  174050  F56C11.6c  
chrI    182240  182390  F56C11.3  
chrI    184080  184230  Y48G1BL.2a  
chrI    190720  190870  Y48G1BL.2a  

并且许多区域(由 chr start end 描述)是重复的,因为它们映射到超过 1 个转录本

例如:

chrI    133600  133750  F53G12.5c.2  
chrI    133600  133750  F53G12.5a  
chrI    133600  133750  F53G12.5b  
chrI    133600  133750  F53G12.5c.1  

我想要的是一个代码,它采用第 1、2、3 列相同的行,并从中提取第 4 列(在本例中为 F53G12.5)的最短公共(public)部分,并输出一个压缩条目,即:

chrI    133600  133750  F53G12.5

或者例如:

chrI    83280   83430   Y48G1C.10a  
chrI    90420   90570   Y48G1C.10b  
chrI    90420   90570   Y48G1C.10c  
chrI    90420   90570   Y48G1C.10a  

它应该给出

 chrI    83280   83430   Y48G1C.10a  
 chrI    90420   90570   Y48G1C.10  

您对此有什么建议吗?非常非常感谢

最佳答案

我怀疑这可以用 Pandas 完成,比这好得多,但我对 Pandas 还不太熟悉,所以......提交时没有调试。

def longest_identical_substring(words):
    result = words[0]
    for idx in range(len(words[0]), 0, -1):
        substrings = [w[:idx] for w in words]
        if max(substrings) == min(substrings): 
            result = substrings[0]
        else:
            return result

transcripts = defaultdict(list)
with open('myfile.csv') as infile:
    reader = csv.reader(infile)
    for row in reader:
        transcripts[row[:3]].append(row[3])
for ((chr, start, end), ts) in transcripts.items():
    print(chr, start, end, longest_identical_substring(ts))

关于python - 如何比较一个文件中的多行并输出组合条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21438989/

相关文章:

linux - 检测 unix 中的目录更改

python - ChatGPT API 定制训练的 AI 聊天机器人对 Python 查询应答 "None"

python - 快速矢量化 datetime.combine()

由于握手问题,PerL SSL 连接尝试失败

unix - sed/awk 或其他 : one-liner to increment a number by 1 keeping spacing characters

c++ - unix中c++多核CPU使用教程

python - MongoDB:创建嵌入文档

python - 使用 VS Code 即时运行 Azure Functions 失败并显示 ECONNREFUSED

perl - 使用 perl HTTP::Daemon 的 HTTP 服务器 - 只能在服务器运行的同一台计算机上工作

perl - 尝试使用 perl 登录网站时出现问题