我正在尝试编写一个打开文件名的函数,读取文件的内容,然后一次打印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
答案 0 :(得分:3)
我对这段代码有几点改变:
three_letters
变量,这就是它重复打印相同内容的原因。打印后,您需要更新three_letters
的值(通过从文件中读取另外三个字符)。open_file
对象。.read(4)
,您可以一次打印4个字母,而不是3个。f = open(filename); ...; f.close()
构造,而不是更传统的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循环将停止。
答案 1 :(得分:0)
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)
只需使用连续循环来测试文件缓冲区是否为空并在迭代期间打印数据。