首页 > 解决方案 > 为什么我的代码没有遍历每一行?尽管剥离了关键错误“\ n”(使用.read()输入的.txt输入)

问题描述

我有一个 .txt 格式的 DNA 序列文件,格式如下:

>seq1
ATATAT
>seq2
GGGGG
>seq3
TTTTT

使用 re.sub,我已经像这样删除了带有“>seq”数字的行,以便像这样只输入 DNA 碱基 A、G、C 和 T 行,然后按如下方式剥离“\n”:

ATATAT
GGGGG
TTTTT
import re
test = re.sub('\ |1|2|3|4|5|6|7|8|9|0|>|s|e|q|:', "", holder)
newone = test.rstrip("\n")

然后我想将其用作我的一个热编码器的输入,该编码器包含在一个 if 语句中(有一个 if 语句来检查 DNA 序列中是否存在任何意外的字母)。到目前为止,它看起来像这样:

for line in newone:

#if undesirable letters are present in sequence, an error message is displayed
    if (bool(result)) == True:
        print("The input sequence is invalid.")

#if sequence is in the correct format, proceed with one hot encoding

    else:   
     #mapping of bases to integers as a dictionary
        bases = "ATCG"
        base_to_integer = dict((i, c) for c, i in enumerate(bases))

    #encoding input sequence as integers
        integer_encoded = [base_to_integer[y] for y in newone]

    #one hot encoding
        onehot_encoded = list()
        for value in integer_encoded:
            base = [0 for x in range(len(bases))]
            base[value] = 1
            onehot_encoded.extend(base)
        print(onehot_encoded)

我可以在 shell 中看到这个错误,但我不知道为什么,因为我想我已经在我的代码中指出“\n”需要被剥离:

Traceback (most recent call last):
  File "C:\Users\Agatha\Documents\testtt.py", line 38, in <module>
    integer_encoded = [base_to_integer[y] for y in newone]
  File "C:\Users\Agatha\Documents\testtt.py", line 38, in <listcomp>
    integer_encoded = [base_to_integer[y] for y in newone]
KeyError: '\n'

我希望我的程序在输入文件的每一行上迭代代码,但我不确定如果删除 \n,我的 for 循环(“for line in newone”)是否会实现这一点,我无法弄清楚如何我可以重新安排它以使其工作。我的目标是让我的输出采用这种格式,其中每个单热编码序列都显示在单独的行上,例如:

[1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0
0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1]

我将不胜感激有关此错误的根源是什么以及如何修复它的任何建议。

标签: pythonone-hot-encodingkeyerror

解决方案


如果我是你,我会使用该.split()方法从你阅读的文本中创建一个列表。

test = re.sub('\ |1|2|3|4|5|6|7|8|9|0|>|s|e|q|:', "", holder)
newone = test.split("\n")

此时newone看起来像['', 'ATATAT', '', 'GGGGG', '', 'TTTTT', '']这样去掉多余的空格:

newone = [x for x in newone if x != '']

现在对于您收到的错误,这是因为您在列表理解(代码的第 38 行)中使用newone的是line. 每个字母line都是字典的键,base_to_integer但您得到的 KeyError 是因为\n不是字典中的键。即使进行了我上面建议的更改,您也会收到错误消息:

KeyError: 'ATATAT'

因此,您应该将此行更改为:

integer_encoded = [base_to_integer[y] for y in line] 

解决这个问题给了我:

[1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0]
[0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1]
[0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0]

希望这可以帮助。


推荐阅读