簡體   English   中英

使用用戶定義的函數進行Python打印

[英]Python printing with user defined functions

我正在嘗試編寫代碼,該代碼將從文件中獲取數據並以不同的方式寫入。 我大部分時間都有代碼,但是當我運行它時,一切都在一行上。

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

當您追加到列表並調用函數時,它將采用函數的文字文本而不是調用它。 使用臨時字符串持有者執行此操作將在連接字符串之前調用該函數。 然后,您可以將字符串追加到列表中

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文件,你需要首先定義列,讓你收集適合該列的格式輸出。

您從未告訴過程序要換行。 您可以在每個字符串中添加或添加特殊的"\\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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM