我正在试着读取蛋白质序列,并给每个氨基酸配上电荷。 序列是以文本(一个字母对应一个氨基酸)的形式写在文件中。
我列出了每封信收费的清单,但我没能看出来:
#! /usr/bin/env python
charge_list = {
'G' : 0.0,
'A' : 0.0,
'V' : 0.0,
'C' : 0.0,
'P' : 0.0,
'L' : 0.0,
'I' : 0.0,
'M' : 0.0,
'W' : 0.0,
'F' : 0.0,
'S' : 0.0,
'T' : 0.0,
'Y' : 0.0,
'N' : 0.0,
'Q' : 0.0,
'K' : 1.0,
'R' : 1.0,
'H' : 1.0,
'D' : -1.0,
'E' : -1.0,
}
def sequence_to_charge(infile):
file1 = open(infile, 'r')
while True:
char = file1.read(1)
if not char:
break
print(char)
print(charge_list[char])
file1.close()
sequence_to_charge("test.dat")
test.dat看起来像GKDE
2注释:
>
如果我跳过print(charge_list[char])
行,我的序列将被打印,但最后有2个空行(不知道为什么):
G
K
D
E
我的最终目标是将费用列表保存在文件2中,该文件看起来像:0 1-1-1
或
0
1
-1
-1
(要有某种数组,我可以在接下来的步骤中使用它)
提前谢谢你!
更容易的做法是先将文件中的数据读入字符串,然后循环遍历字符串中的字符:
def sequence_to_charge(infile):
with open(infile, 'r') as file1:
chars = file1.read()
for char in chars:
if char in charge_list:
print(char, charge_list[char])
sequence_to_charge('text.txt')
打印:
G 0.0
K 1.0
D -1.0
E -1.0
您可以使用计数器快速完成此操作:
from collections import Counter
def sequence_to_charge(infile):
with open(infile, 'r') as file:
count = Counter(file.read())
return count
sequence_to_charge("test.dat")
编辑:如果您需要将其作为字典,您可以简单地对结果调用dict