【问题标题】:Loop through fixed number of chars in text file循环遍历文本文件中固定数量的字符
【发布时间】:2020-09-04 19:31:57
【问题描述】:

假设我有一个带有连续字符(没有空格或换行符)的file.txt,如下所示:

ABCDHELOABCDFOOOABCD

我想遍历文件,遍历固定数量的 4 个字符,如下所示:

[ABCD, HELO, ABCD, FOOO, ABCD] 

常规循环不行:我怎样才能做到这一点?

【问题讨论】:

  • HELLO 不是 4 个字符
  • 究竟为什么“常规循环”不起作用?您在考虑什么“常规循环”?另外,你试过什么?

标签: python loops file


【解决方案1】:

您可以使用TextIOWrapper.read 的可选size 参数一次从文件中读取四个字符。这里我使用的是 Python 3.8 的“海象”运算符,但这不是严格要求的:

with open("file.txt", "r") as file:
    while chunk := file.read(4):
        print(chunk)

【讨论】:

    【解决方案2】:

    这样的简单循环就可以了。不是很pythonic,但可以完成工作

    s = 'ABCDHELLOABCDFOOOABCD'
    for i in range(0,len(s),3):
        print(s[i:i+3])
    

    【讨论】:

      【解决方案3】:

      内置textwrap 模块,具有wrap 功能。因此,可以通过这种方式完成任务而无需循环:

      import textwrap
      
      with open('file.txt', 'r') as f:
          chunked = textwrap.wrap(f.read(), 4)
      
      # chunked -> ['ABCD', 'HELO', 'ABCD', 'FOOO', 'ABCD']
      

      【讨论】:

        【解决方案4】:

        假设您已读取文件的输入并将整个块转换为一个称为数据的字符串,您可以像这样对其进行迭代:

        individual_strings = data[::4]
        

        这会根据需要为您提供一个字符串列表,然后您可以循环访问!

        【讨论】:

          【解决方案5】:

          试试这个:

          with open('file.txt', 'r') as f:
             content = f.read()
             splited_by_four_letters = [content[i:i+4] for i in range(len(content))]
             // do whatever you want with your data here
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2014-12-15
            • 1970-01-01
            • 2012-11-15
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-06-19
            相关资源
            最近更新 更多