python - 逐个字符读取文件并从字典中赋值
问题描述
我正在尝试读取蛋白质序列并将电荷分配给每个氨基酸。序列以文本形式(一个字母对应一个氨基酸)写入文件。
我列出了每封信收费的清单,但我没有阅读:
#! /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
推荐阅读
- bash - 使用 ssh 运行 ESP 命令
- c - 在 char 指针中间添加 \0
- javascript - Promise.all 依赖于第一个承诺响应对第二个承诺
- c# - Npgsql.PostgresException:关系“表名”不存在'
- swift - 如何对两个不同的日期进行排序?
- python - 如何在 Python 中创建相同的数字模式列表?
- api - Swagger 中 start_date/timestamp 的格式?
- sql-server - STRING_SPLIT 与行号
- python - 尽管一切正常,但 KerasClassifier 无法拟合模型
- php - 在 PHP 中运行原始的外部 HTML