[英]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.