首页 > 解决方案 > 我想使用 sum 函数来计算特定字符的多次出现,但我的脚本只适用于一个字符

问题描述

这个脚本应该计算蛋白质的总重量,所以我决定计算脚本中某些字符的出现次数。然而,只有第一个等式产生的结果导致总重量为相同的值(第一个下的所有值都为零,这绝对是不正确的)。如何让我的脚本关注其他行???这是一个缩短的版本:

akt3_file = open('AKT3 fasta.txt', 'r') #open up the fasta file

for line in akt3_file:

   ala =(sum(line.count('A') for line in akt3_file)*89*1000) #this value is 1780000
   arg =(sum(line.count('R') for line in akt3_file)*174*1000)
   asn =(sum(line.count('N') for line in akt3_file)*132*1000)
   asp =(sum(line.count('D') for line in akt3_file)*133*1000)
   asx =(sum(line.count('B') for line in akt3_file)*133*1000)

protein_weight = ala+arg+asn+asp+asx
print(protein_weight) # the problem is that this value is also 1780000
akt3_file.close() #close the fasta file

标签: pythonfunctionfor-loopvariablessum

解决方案


您遇到的问题是您尝试多次迭代文件的行。虽然这实际上是可能的(与大多数迭代器不同,文件对象可以用 倒带seek),但您没有正确执行此操作,因此除了第一次之外的所有迭代都看不到任何数据。

在这种情况下,您可能根本不需要遍历这些行。只需将文件的全文读入一个字符串,然后从该字符串中计算出您想要的字符:

with open('AKT3 fasta.txt', 'r') as akt_3file:  # A with is not necessary, but a good idea.
    data = akt_3file.read()        # Read the whole file into the data string.

ala = data.count('A') * 89 * 1000  # Now we can count all the occurrences in all lines at
arg = data.count('R') * 174 * 1000 # once, and there's no issue iterating the file, since
asn = data.count('N') * 132 * 1000 # we're not dealing with the file any more, just the
asp = data.count('D') * 133 * 1000 # immutable data string.
asx = data.count('B') * 133 * 1000

推荐阅读