首页 > 解决方案 > 逐个字符读取文件并从字典中赋值

问题描述

我正在尝试读取蛋白质序列并将电荷分配给每个氨基酸。序列以文本形式(一个字母对应一个氨基酸)写入文件。

我列出了每封信收费的清单,但我没有阅读:

#! /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 条评论:

先感谢您!

标签: pythonarraysdictionary

解决方案


首先将文件中的数据读入字符串,然后遍历字符串中的字符更容易:

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

推荐阅读