我想知道如何使用python或R连接外显子/ DNA fasta文件。
到目前为止,我真的很喜欢在cbind方法中使用R ape包,完全是因为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")
示例:
exon1.txt
>sp1
AAAA
>sp2
CCCC
exon2.txt
>sp1
AGG-G
>sp2
CTGAT
>sp3
CTTTT
输出文件:
>sp1
AAAAAGG-G
>sp2
CCCCCTGAT
>sp3
----CTTTT
到目前为止,当我有多个外显子文件(尝试找出一个循环来打开并执行目录中以.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。
答案 0 :(得分:1)
如果您更喜欢使用Linux,则需要
cat exon1.txt exon2.txt > outfile
如果只想使用outfile中的唯一记录
awk '/^>/{f=!d[$1];d[$1]=1}f' outfile > sorted_outfile
答案 1 :(得分:0)
我刚刚在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
我使用ŁukaszRogalski的代码来回答Reading a fasta file format into Python dict
。