如何解决字典无法处理来自 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()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。