如何迭代两个文件并打印它们的差异并显示位置

2024-06-25 06:54:00 发布

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

我在编写这个程序,我有两个不同的DNA序列存储在两个不同的文件中。我在比较DNA序列,看看哪些字符是不同的,在哪个位置是不同的。 这是我到目前为止的代码,但是我没有得到我想要的输出

   WildDNAf = raw_input("Enter Wild DNA file: " )
   wildDNA = open(WildDNAf).read()
   MutDNAf = raw_input("Enter Mut DNA file: ")
   mutDNA = open (MutDNAf).read()


   dnacount = 0
   for i in range(len(wildDNA)):
       if wildDNA[i] != mutDNA:
           print i + 1 , wildDNA[i], mutDNA[i]
          dnacount = dnacount +1
   print "There are", dnacount, "Mutations"

这就是我得到的:

There are 2589 Mutations
2590 T T
There are 2590 Mutations
2591 T T
There are 2591 Mutations
2592 G T
There are 2592 Mutations
2593 A G
There are 2593 Mutations
2594 A A
There are 2594 Mutations

我试图得到一个输出,显示在两个序列之间发现的任何突变的列表,以及在哪些位置发现突变。 DNA序列的文件可以在这里找到https://uploadfiles.io/wpueyhttps://ufile.io/dzzvi


Tags: 文件inputraw序列openarednafile
1条回答
网友
1楼 · 发布于 2024-06-25 06:54:00

我认为问题在于这一行,它将wildDNA的单个字符与mutDNA中的整个字符串进行比较

if wildDNA[i] != mutDNA:

您可能需要这样做,它将比较每个字符的单个字符(在同一索引处)

if wildDNA[i] != mutDNA[i]:

还要确保你的缩进是正确的。由于缩进,您共享的内容不是有效的Python,您的输出使我认为print语句在循环内,即使您共享的代码在循环外

更新

带输出的完整工作代码(Python3.x):

def read_dna_file(filename):
    with open(filename, 'rt') as f:
        return ''.join(line.strip() for line in f.readlines()[1:])

a = read_dna_file('wild.fasta')
b = read_dna_file('mut.fasta')

assert len(a) == len(b)

count = 0

for i in range(len(a)):
    if a[i] != b[i]:
        print(i, a[i], b[i])
        count += 1

print("There are {} mutations.".format(count))

# Output:
# 0 T A
# 87 A G
# 88 A G
# 1307 G C
# 2367 T C
# There are 5 mutations.

请注意,每个文件的顶部都有一行内容不同(长度也不同)。因此,在进行逐字符比较之前,您需要跳过这一点,否则文件中的几乎所有内容都将无法匹配。我的read_dna_file函数跳过第一行,然后忽略文件中的换行符

相关问题 更多 >