字典无法处理来自 txt 文件的 DNA 字符串

问题描述

当我使用文本文件中的 DNA 字符串时,使用字典的函数返回 KeyFile 错误“\n”,但当我手动输入 DNA 字符串时不会返回:


DNA = open(r"C:\Users\CP\Desktop\Python\rosalind_revc.txt","r")
DNA = DNA.read()
DNA.replace(' ','')
print(DNA)
# Output works when I manually type a DNA string,such as the one below in the comment
# DNA = "TCAGCAT"

def complement(s): 
    
    # Create a dictionary with all the complementary base pairings
    basecomplement = {'A':'T','C':'G','G':'C','T':'A'}
    
    # Turn the input DNA into a list
    letters = list(s)
    
    # Use the dictionary to replace each list element
    n = [basecomplement[b] for b in letters]
    
    # Make the function return the list as a string
    # We want no spaces in the new DNA string,so there are no spaces inside
    # the quotation marks--that's where the "separator" is.
    return ''.join(n)

def revcom(s):
    return(complement(s[::-1]))

DNA_revcom = revcom(DNA)

print(DNA_revcom)

我是 Python 编程的新手,所以我感谢任何反馈!

解决方法

文件中的行有一个 newline character,与您手动输入的字符串不同。因此您需要删除换行符,您可以使用 rstrip 来完成,如下所示:

DNA = DNA.read().rstrip()