【问题标题】:Python print .psl format without quotes and commasPython 打印不带引号和逗号的 .psl 格式
【发布时间】:2018-04-08 21:52:52
【问题描述】:

我正在使用 python3 开发一个 linux 系统,文件格式为遗传学常见的.psl 格式。这是一个制表符分隔文件,其中包含一些以逗号分隔值的单元格。下面是一个小示例文件,其中包含 .psl 的一些功能。

输入.psl

1 2 3 x read1 8,9, 2001,2002,
1 2 3 mt read2 8,9,10 3001,3002,3003
1 2 3 9 read3 8,9,10,11 4001,4002,4003,4004
1 2 3 9 read4 8,9,10,11 4001,4002,4003,4004

我需要过滤此文件以仅提取感兴趣的区域。在这里,我只提取第四列中值为 9 的行。

import csv

def read_psl_transcripts():
    psl_transcripts = []
    with open("input.psl") as input_psl:
        csv_reader = csv.reader(input_psl, delimiter='\t')
        for line in input_psl:
        #Extract only rows matching chromosome of interest
        if '9' == line[3]:
            psl_transcripts.append(line)
    return psl_transcripts

然后我需要能够以制表符分隔的格式打印或写入这些选定的行,该格式与输入文件的格式相匹配,无需添加额外的引号或逗号。我似乎无法正确理解这部分,并且总是添加额外的括号、引号和逗号。下面是使用 print() 的尝试。

outF = open("output.psl", "w")
for line in read_psl_transcripts():
    print(str(line).strip('"\''), sep='\t')

非常感谢任何帮助。以下是所需的输出。

1 2 3 9 read3 8,9,10,11 4001,4002,4003,4004
1 2 3 9 read4 8,9,10,11 4001,4002,4003,4004

【问题讨论】:

    标签: python printing bioinformatics genetics


    【解决方案1】:

    你也许可以用一个简单的 awk 语句来解决你的问题。

    awk '$4 == 9' input.pls > output.pls
    

    但是使用 python 你可以这样解决它:

    write_pls = open("output.pls", "w")
    
    with open("input.pls") as file:
        for line in file:
            splitted_line = line.split()
            if splitted_line[3] == '9':
                out_line = '\t'.join(splitted_line)
                write_pls.write(out_line + "\n")
    
    write_pls.close()
    

    【讨论】:

      猜你喜欢
      • 2023-01-17
      • 2021-08-27
      • 2022-01-10
      • 2022-10-13
      • 1970-01-01
      • 2017-02-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多