在Python或R中连接多个DNA序列的文本文件?

2024-05-29 02:21:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何使用Python或R连接exon/DNA fasta文件

示例文件:

到目前为止,我非常喜欢为cbind方法使用rape包,这仅仅是因为fill.with.gaps=TRUE属性。当一个物种缺失外显子时,我真的需要插入缝隙。在

我的代码:

ex1 <- read.dna("exon1.txt", format="fasta")
ex2 <- read.dna("exon2.txt", format="fasta")
output <- cbind(ex1, ex2, fill.with.gaps=TRUE)
write.dna(output, "Output.txt", format="fasta")

示例:

外显1.txt

^{pr2}$

exon2.txt文件

>sp1
AGG-G
>sp2
CTGAT
>sp3
CTTTT

输出文件:

>sp1
AAAAAGG-G
>sp2
CCCCCTGAT
>sp3
----CTTTT

到目前为止,当我有多个exon文件(试图找出一个循环来打开并执行目录中以.fa结尾的所有文件的cbind方法)时,我在尝试应用此技术时遇到了困难,有时并不是所有文件都有长度相同的外显子,因此DNAbin停止工作。在

到目前为止,我已经:

file_list <- list.files(pattern=".fa") 

myFunc <- function(x) {
   for (file in file_list) {
     x <- read.dna(file, format="fasta")
     out <- cbind(x, fill.with.gaps=TRUE)
     write.dna(out, "Output.txt", format="fasta")
   }
}

然而,当我运行这个程序并检查我的输出文本文件时,它遗漏了许多外显子,我认为这是因为并非所有的文件都具有相同的外显子长度。。。或者我的剧本在某个地方失败了,我想不通

有什么想法吗?我也可以试试Python。在


Tags: 文件txttrueformatreadwithfilllist
2条回答

如果您更喜欢使用Linux一行程序

      cat exon1.txt exon2.txt > outfile

如果您只想从输出文件使用唯一的记录

^{pr2}$

我刚刚在Python 3中给出了这个答案:

def read_fasta(fasta): #Function that reads the files
  output = {}
  for line in fasta.split("\n"):
    line = line.strip()
    if not line:
      continue
    if line.startswith(">"):
      active_sequence_name = line[1:]
      if active_sequence_name not in output:
        output[active_sequence_name] = []
      continue
    sequence = line
    output[active_sequence_name].append(sequence)
  return output

with open("exon1.txt", 'r') as file: # read exon1.txt
  file1 = read_fasta(file.read())
with open("exon2.txt", 'r') as file: # read exon2.txt
  file2 = read_fasta(file.read())

finaldict = {}                                     #Concatenate the
for i in list(file1.keys()) + list(file2.keys()):  #both files content
  if i not in file1.keys():
    file1[i] = ["-" * len(file2[i][0])]
  if i not in file2.keys():
    file2[i] = ["-" * len(file1[i][0])]
  finaldict[i] = file1[i] + file2[i]

with open("output.txt", 'w') as file:  # output that in file 
  for k, i in finaldict.items():       # named output.txt
    file.write(">{}\n{}\n".format(k, "".join(i))) #proper formatting

很难对它进行全面的评论和解释,这可能对你没有帮助,但这总比什么都没有要好:p

我使用了Łukasz Rogalski的代码从应答到Reading a fasta file format into Python ^{}。在

相关问题 更多 >

    热门问题