【问题标题】:Python KeyError: '\n'Python 密钥错误:'\n'
【发布时间】:2015-12-14 08:32:03
【问题描述】:

我使用下面的脚本从 fastq 文件中提取分子条形码。但是,我不断收到以下关键错误。

File "extractMolecularBarcode.py", line 42, in <module>
    dicoBarcode[barcode] += 1
KeyError: '\n'

我知道关键错误意味着字典中未定义某些内容,但我无法找出问题所在。你能帮忙吗?非常感谢!

这是脚本:

import sys, itertools


iFastq=open(sys.argv[1], 'r')
oFastq=open(sys.argv[2], 'w')
oBarcode=open(sys.argv[3], 'w')
oLigation=open(sys.argv[4], 'w')

dicoBarcode={}
dicoLigation={}
nct='ACTGN'
for barcode in list(itertools.product(nct, repeat=6)):
    dicoBarcode["".join(barcode)] = 0
    dicoLigation["".join(barcode)] = 0


header= iFastq.readline().rstrip()
while header != '':
    totseq= iFastq.readline()
    plus = iFastq.readline()
    qual = iFastq.readline()
    barcode = totseq[0:6]
    ligation = totseq[3:9]
    seq = totseq[6:]
    oFastq.write(header.split(" ")[0]+'_MolecularBarcode:'+barcode+' '+header.split(" ")[1]+'\n')
    oFastq.write(seq)
    oFastq.write(plus)
    oFastq.write(qual[6:])
    header= iFastq.readline().rstrip()

    dicoBarcode[barcode] += 1
    if len(seq) >= 4 :
    dicoLigation[ligation] += 1

for barcode, times in dicoBarcode.items():
oBarcode.write("%s\t%s\n" % (barcode, str(times)))

for ligation, times in dicoLigation.items():
oLigation.write("%s\t%s\n" % (ligation, str(times)))

【问题讨论】:

    标签: python keyerror


    【解决方案1】:

    你的文件中有一个换行符,当你使用时

     dicoBarcode[barcode] += 1
    

    条形码值是换行符或'\n'会导致错误!

    您可以通过提供默认值来克服它:

    discoBarcode.get(barcode,YOURDEFAULT)
    

    或者您可以先删除换行符然后处理文件;)

    yourfile.readline().rstrip("\n")
    

    【讨论】:

    • 感谢您的回答。您对消除这个问题有什么建议吗?
    • 我无法理解带有 dicobarcode.get(barcode, yourdefault) 的那个。你能再解释一下吗?谢谢!
    【解决方案2】:

    问题是你没有在你的barcode 值来自的实际行上调用rstrip()。您需要编辑这些行:

    totseq= iFastq.readline()
    plus = iFastq.readline()
    qual = iFastq.readline()
    

    所以它们看起来像这样:

    totseq= iFastq.readline().rstrip()
    plus = iFastq.readline().rstrip()
    qual = iFastq.readline().rstrip()
    

    【讨论】:

    • 感谢您的回答。当我在其他问题中寻找关键错误的答案时,我尝试过 rstrip,但它仍然给我同样的错误:/
    • KeyError 仅表示该特定键 \n 不在您的字典中,因此读取/增量失败。我试图解决原来的问题。
    • 我再次尝试在两个 rstrip 中添加 \n ('while' 开始之前的一个和 'while' 循环结束的那个)。它没有用。它再次给了我同样的错误。在上一步中,我做了适配器移除。也许那一步有问题导致这个错误?
    • @mordel 对不起,我在 2 个方面弄错了。编辑了答案。 1. rstrip() 删除 \n 和 2. 您从另一个没有 rstripreadline() 获取您的条形码值
    • 我按照您的建议将 rstrip 添加到这三行(totseq、plus 和 qual)的末尾。仍然没有任何改变:(
    猜你喜欢
    • 2013-08-04
    • 2016-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-20
    相关资源
    最近更新 更多