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

时间:2018-11-02 15:49:00

标签: 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_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()

当我运行它时,它应该输出一个看起来像this的文件,但是我的代码最终将每个单词都放在this这样的顶行 我觉得它与write_results函数有关,但是我只知道如何写入文件。

我犯的第二个错误是我没有在append语句中正确调用函数。我尝试了串联,并尝试格式化了字符串,但是现在我遇到了需要做的事情。

3 个答案:

答案 0 :(得分:1)

写入文件时,每次要在写入文件的新行中添加内容时,都需要在字符串末尾加上'\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)

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

答案 1 :(得分:1)

read_data()实际上不读取任何内容(只是打开文件)。它应该读取文件并返回其内容:

def read_data(filename):
    with open(filename, "r") as f:
        return f.read()

get_dna_stats()不会获得DNA的统计信息(不会返回任何内容,也不计算“ A”或“ T”,仅检查它们是否存在,nucleotide_content是计算出来的,但从不使用或返回。它应该可能计数并返回结果:

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_dna_complement()get_rna_sequence():您不能append输入字符串。而是使用

dna_complement += "T"

...而不是break,您可以添加"?"来表示失败的翻译,或者添加raise ValueError("invalid letter in 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_exon(),我不知道这是什么,但是想必您只想从startend的子字符串,可以通过以下方式实现:

def extract_exon(dna_strand, start, end):
    return dna_strand[start:end]  # possibly end+1, I don't know exons

我猜想在calculate_exon_pctg()中,您希望exons_length += len(i)求和外显子的长度。您可以通过使用内置函数sum来实现:

exons_length = sum(exons)

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

main()不会传递任何数据。它将read_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文件,则需要首先定义列,并使收集的所有输出都适合该列格式。

答案 2 :(得分:0)

您从未告诉程序要换行。您可以在每个字符串中附加或添加特殊的"\n"字符,也可以通过与系统无关的方式执行此操作

import os

在文件顶部,并编写如下的write_results函数:

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")