Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/.htaccess/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用用户定义函数的Python打印_Python - Fatal编程技术网

使用用户定义函数的Python打印

使用用户定义函数的Python打印,python,Python,我正在尝试编写一个代码,从文件中获取数据并以不同的方式编写。我大部分都有代码,但当我运行它时,所有内容都在一行上 import csv #Step 4 def read_data(filename): try: data = open("dna.txt", "r") except IOError: print( "File not found") return data #Step 5 def get_dna_stats(dna_stri

我正在尝试编写一个代码,从文件中获取数据并以不同的方式编写。我大部分都有代码,但当我运行它时,所有内容都在一行上

import csv
#Step 4
def read_data(filename):
    try:
        data = open("dna.txt", "r")
    except IOError:
        print( "File not found")
    return data

#Step 5
def get_dna_stats(dna_string):
    a_letters = ""
    t_letters = ""
    if "A" in dna_string:
        a_letters.append("A")
    if "T" in dna_string:
        t_letters.append("T")
    nucleotide_content = ((len(a_letters) + len(t_letters))/len(dna_string))

#Step 6
def get_dna_complement(dna_string):
    dna_complement = ""
    for i in dna_string:
        if i == "A":
            dna_complement.append("T")
        elif i == "T":
            dna_complement.append("A")
        elif i == "G":
            dna_complement.append("C")
        elif i == "C":
            dna_complement.append("G")
        else:
            break
    return dna_complement

#Step 7
def print_dna(dna_strand):
    dna_complement = get_dna_complement(dna_strand)
    for i in dna_strand:
        for j in dna_complement:
            print( i + "=" + j)


#Step 8
def get_rna_sequence(dna_string):
    rna_complement = ""
    for i in dna_string:
        if i == "A":
            rna_complement.append("U")
        elif i == "T":
            rna_complement.append("A")
        elif i == "G":
            rna_complement.append("C")
        elif i == "C":
            rna_complement.append("G")
        else:
            break
    return rna_complement

#Step 9
def extract_exon(dna_strand, start, end):
    return (f"{dna_strand} between {start} and {end}")

#Step 10
def calculate_exon_pctg(dna_strand, exons):
    exons_length = 0
    for i in exons:
        exons_length += 1
    return exons_length/ len(dna_strand)

#Step 11
def format_data(dna_string):
    x = "dna_strand"[0:62].upper()
    y = "dna_strand"[63:90].lower()
    z = "dna_strand"[91:-1].upper()
    return x+y+z

#Step 12
def write_results(output, filename):
    try:
        with open("output.csv","w") as csvFile:
            writer = csv.writer(csvFile)
            for i in output:
                csvFile.write(i)
    except IOError:
        print("Error writing file")

#Step 13
def main():
    read_data("dna.txt")
    output = []
    output.append("The AT content is" + get_dna_stats() + "% of the DNA sequence.")
    get_dna_stats("dna_sequence")
    output.append("The DNA complement is " + get_dna_complement())
    get_dna_complement("dna_sequence")
    output.append("The RNA sequence is" + get_rna_sequence())
    get_rna_sequence("dna_sequence")
    exon1 = extract_exon("dna_sequence", 0, 62)
    exon2 = extract_exon("dna_sequence", 91, len("dna_sequence"))
    output.append(f"The exon regions are {exon1} and {exon2}")
    output.append("The DNA sequence, which exons in uppercase and introns in lowercase, is" + format_dna())
    format_data("dna_sequence")
    output.append("Exons comprise " + calculate_exon_pctg())
    calculate_exon_pctg("dna_sequence",[exon1, exon2])
    write_results(output, "results.txt")
    print("DNA processing complete")

#Step 14
if __name__ == "__main__":
    main()
当我运行它时,它应该输出一个看起来像的文件,但我的代码最后把每个字都放在顶行,就像 我觉得这与
write\u results
函数有关,但我只知道如何写入文件


我犯的第二个错误是在append语句中没有正确调用函数。我尝试过连接字符串,也尝试过格式化字符串,但现在我遇到了一个需要执行的路障。

当您写入文件时,每次您希望在写入的文件中的新行上有内容时,都需要将
'\n'
连接到字符串的末尾

例如:

output.append("The AT content is" + get_dna_stats() + "% of the DNA sequence." + '\n')
为了解决您的第二个问题,我将您的代码更改为:

temp = "The AT content is" + get_dna_stats() + "% of the DNA sequence." + '\n'
output.append(temp)
def write_results(output, filename):
    try:
        with open("output.csv","w") as csvFile:
            writer = csv.writer(csvFile)
            for i in output:
                csvFile.write(i)
                os.write(csvFile, os.linesep)  # Add this line! It is a system agnostic newline
    except IOError:
        print("Error writing file")

当您附加到列表并调用函数时,它将采用函数的文本而不是调用它。使用临时字符串保持器执行此操作将在串接字符串之前调用函数。然后,您可以将字符串附加到列表中

您从未告诉您的程序生成新行。您可以将特殊的
“\n”
字符附加或前置到每个字符串,也可以通过执行以下操作以系统无关的方式执行此操作:

导入操作系统

在文件的顶部,写入write_结果的功能如下:

temp = "The AT content is" + get_dna_stats() + "% of the DNA sequence." + '\n'
output.append(temp)
def write_results(output, filename):
    try:
        with open("output.csv","w") as csvFile:
            writer = csv.writer(csvFile)
            for i in output:
                csvFile.write(i)
                os.write(csvFile, os.linesep)  # Add this line! It is a system agnostic newline
    except IOError:
        print("Error writing file")
read\u data()
实际上不读取任何内容(只打开文件)。它应该读取文件并返回其内容:

def read_data(filename):
    with open(filename, "r") as f:
        return f.read()
get\u dna\u stats()
不会获取dna统计信息(不会返回任何信息,也不会计算“A”或“t”,只检查它们是否存在,
nucleotide\u内容
已计算,但从未使用或返回。它可能会计算并返回结果:

def get_dna_stats(dna_string):
    num_a = dna_string.count("A")
    num_t = dna_string.count("T")
    nucleotide_content = (num_a + num_t) /float(len(dna_string))
    return nucleotide_content
get\u-dna\u-complete()
get\u-rna\u-sequence()
:不能
附加到字符串中。请使用

dna_complement += "T"
…您可以附加一个
“?”
来表示转换失败,或者
增加值错误(“DNA中的无效字母:“+i”)

print_dna()
有点有趣。我猜您希望“压缩”dna的每个字母及其补码。巧合的是,您可以使用
zip
函数来实现这一点:

def print_dna(dna_strand):
    dna_complement = get_dna_complement(dna_strand)
    for dna_letter, complement in zip(dna_strand, dna_complement):
        print(dna_letter + "=" + complement)
至于
extract\u exon()
,我不知道这是什么,但您可能只需要从
start
end
的子字符串,这是通过以下方式实现的:

def extract_exon(dna_strand, start, end):
    return dna_strand[start:end]  # possibly end+1, I don't know exons
我猜在
calculate\u exon\u pctg()
中,您希望
exons\u length+=len(I)
对外显子的长度求和。您可以通过使用内置函数
sum
来实现这一点:

exons_length = sum(exons)
在函数
format_data()
中,松开双引号。您需要变量

main()
不会传递任何数据。它应该将
read\u data()
的结果传递给所有其他函数:

def main():
    data = read_data("dna.txt")                                                 
    output = []
    output.append("The AT content is " + get_dna_stats(data) + "% of the DNA sequence.")
    output.append("The DNA complement is " + get_dna_complement(data))
    output.append("The RNA sequence is" + get_rna_sequence(data))
    ...
    write_results(output, "results.txt")                                        
    print("DNA processing complete")                                            
这一阶段的关键是理解函数调用是如何工作的:它们将数据作为输入参数,并返回一些结果。您需要a)提供输入数据,b)捕获结果

write_results()
-从您的屏幕截图来看,您似乎想要编写一个普通的旧文本文件,但您使用的是
csv.writer()
(它写入csv,即表格数据)。要写纯文本

def write_results(output, filename):
    with open(filename, "w") as f:
        f.write("\n".join(output))  # join output lines with newline
        f.write("\n")  # extra newline at file's end

如果确实需要CSV文件,则需要首先定义列,并使收集的所有输出符合该列格式。

如果
open
引发
IOError
,您认为
read\u data
会返回什么<代码>数据从未在这种情况下定义。更详细地说,您的错误处理还没有完全考虑清楚。如果发生错误,则必须以一种您的程序可以继续而不产生进一步错误的方式来处理,或者如果错误很严重(例如,如果您的程序只解析输入,但没有输入),则程序应该干净地终止,理想情况下是在打印有意义的错误消息之后。要终止,您必须首先导入sys,然后执行do
sys.exit(1)
,其中1是一个任意错误代码,可以是除0之外的任何整数,0通常保留用于无错误终止(如果没有错误,请使用0)。