簡體   English   中英

使用Python一次從文件中打印字母3個字母

[英]Printing letters from a File 3 Letters at a Time in Python

我試圖編寫一個打開文件名,讀取文件內容,然后一次打印3個字母的內容的函數。 這是我嘗試過的:

def trigram_printer(filename):

    open_file = open(filename)
    copy = open_file
    three_letters = copy.read(4)


    for contents in copy:
        print(three_letters)

    open_file.close

關於此代碼,我需要更改幾件事:

  • 您永遠不會更新three_letters變量,這就是為什么它重復打印相同內容的原因。 打印后,您需要更新three_letters的值(通過從文件中讀取另外三個字符)。
  • 當我直接使用open_file對象時,就可以復制它。
  • 通過執行.read(4) ,您一次打印4個字母的內容,而不是3個字母。
  • 您正在使用f = open(filename); ...; f.close() f = open(filename); ...; f.close() f = open(filename); ...; f.close()構造,而不是將with open(filename) as f; ...的更常規的構造with open(filename) as f; ... with open(filename) as f; ...

考慮到這些想法,這就是我編寫三字母打印機的方法:

def trigram_printer(filename):
    """Prints the contents of <filename>, three characters at a time."""
    with open(filename, 'r') as f:
        three_letters = f.read(3)

        while three_letters:
            print(three_letters)
            three_letters = f.read(3)

關鍵部分是每次打印three_letters時,此函數都會從文件中讀取接下來的三個字符。 當字符用完時, three_letters將為空字符串,而while循環將停止。

copy僅指向open_file和您的打印中的行數的信件copy

with open('test.txt') as open_file:
    data = open_file.read(3)

    while data != '':
        print(data) # print 3-gram
        data = open_file.read(3)

只需使用連續循環來測試文件緩沖區是否為空並在迭代過程中打印數據。

暫無
暫無

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

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