我正在尝试编写一个函数来打开文件名,读取文件内容,然后一次打印 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()
结构,而不是更传统的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 循环将停止。
关于python - 在 Python 中一次打印文件中的字母 3 个字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29264024/