【问题标题】:How to get a string to split into chunks of five?如何让一个字符串分成五个块?
【发布时间】:2016-01-30 19:53:47
【问题描述】:

所以程序会读取一个带有字符串的文件。然后该字符串将被保存到另一个文件,但该字符串将被分成 5 个组。

示例。

假设file1.txt 的内容是thecatsatonthemat,那么file2.txt 的内容就是theca tsato nthem at

【问题讨论】:

  • 自己写一些代码怎么样?如果您遇到特定问题,我们很乐意为您提供帮助。
  • 这是具体问题

标签: python string chunking


【解决方案1】:

这是一个枚举器,它将为您提供 5 个字符块:

def chunk(l):
    for i in range(0, len(l), 5):
        yield l[i:i+5]

像这样使用它:

>>> l = 'abcdefghijqlmnopqrstuvwxyz'
>>> for sub in chunk(l):
>>>     print(sub)

abcde
fghij
klmno
pqrst
uvwxy
z

【讨论】:

  • 恭喜,您的答案在下面列出(:github.com/drathier/stack-overflow-import
  • 在 Python 2 中,将 range 替换为 xrange 以避免在输入较长时创建较长的临时列表。
  • 这并不直接回答问题,例如OP 指定应该从文件中读取输入。
【解决方案2】:

这样的?

>>> a = "123456789012345678901234567890"
>>> while len(a)>0:
...     print a[0:5]
...     a=a[5:]
...
12345
67890
12345
67890
12345
67890

【讨论】:

  • 这对于长字符串来说非常慢 (O(len(a)**2)),因为 `a[5:]' 会复制几乎整个字符串。
【解决方案3】:

你可以做这样的事情。 file1.txt 将是检索字符串的文件。 file2.txt 将是写入拆分字符串的文件。

注意:此代码假定文本文件 (file1.txt) 没有空格或换行符。

line = ''
with open('file1.txt', 'r') as fr:
    line = fr.read()
fr.close()

modified_str = ''
for i in range(0, len(line), 5):
    modified_str += line[i:i + n] + ' '
modified_str = modified_str[:len(modified_str) - 1] # Remove the trailing white space

with open('file2.txt', 'w') as fw:
    fw.write(modified_str)
fw.close()

让我们假设file1.txt 的内容是thecatsatonthemat。运行该代码,file2.txt 现在将包含theca tsato nthem at

【讨论】:

  • 这不起作用,它引发了NameError: name 'n' is not defined
【解决方案4】:

如果内存中有字符串并且需要内存中的输出,请使用 Steven Burnap 的答案。

如果您需要读取和写入文件,这里有一个使用很少 (O(1)) 内存且适用于 Python 2 和 3 的快速解决方案:

with open('file1.txt') as f:
  with open('file2.txt', 'w') as nf:
    item = f.read(5)
    nf.write(item)
    while len(item) == 5:
      item = f.read(5)
      if not item:
        break
      nf.write(' ')
      nf.write(item)

【讨论】:

    【解决方案5】:

    文件data.txt的内容thecatsatonthemat

    with open('data.txt', 'r') as f:
        data = f.read()
    new_string = ''
    for i,val in enumerate(data):
        if i%5 == 0 and i != 0:
            new_string += ' ' + val
        else:
            new_string += val
    with open('new_data.txt', 'w') as f:
        f.write(new_string)
    

    new_data.txt 的内容

    theca tsato nthem at
    

    【讨论】:

    • 这是不正确的,它在new_data.txt的开头添加了一个额外的空格。
    • @pts:更正了解决方案。使用 lstrip() 将删除字符串开头的空格
    • 还是不正确,因为输入以空格开头时lstrip会去掉多余的空格。
    • @pts:更新解决方案
    • 解决方案现在是正确的。它将整个输入文件读入内存,因此如果文件大小为n,它使用O(n) 内存。查看我的解决方案,减少 (O(1)) 内存使用量。
    猜你喜欢
    • 2021-02-10
    • 1970-01-01
    • 2021-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-03
    • 1970-01-01
    相关资源
    最近更新 更多