python - 在 Python 中一次打印文件中的字母 3 个字母

标签 python file

我正在尝试编写一个函数来打开文件名,读取文件内容,然后一次打印 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/

相关文章:

python - Tornado:识别/跟踪 websocket 的连接?

python - 在Python中增量计算大数组的汇总统计

python - 如何在 Python 中使用 for 循环的每次迭代创建一个新的数据框

构造 URL 对象时出现 Java MalformedURL 异常

android - 使用 DefaultHTTPClient 和抢先身份验证下载文件

c++ - 从文件中读取多个单词

python - 如何根据pandas中的条件映射两行不同的数据框

python - 当 git commit-msg Hook 失败时,如何恢复提交消息?

java - 为什么我的文本文件总是空的?

python读取文件