简体   繁体   English

如何将一个字符串拆分为五个?

[英]How to get a string to split into chunks of five?

So the program would read a file with a string. 因此,程序将读取带有字符串的文件。 That string would then be saved to another file but the string would be split into groups of 5. 该字符串然后将保存到另一个文件,但该字符串将分为5组。

Example. 例。

Given that the content of file1.txt will be thecatsatonthemat , the content of file2.txt would then be theca tsato nthem at . 假设file1.txt的内容是file2.txt ,那么thecatsatonthemat的内容将是theca tsato nthem at

Here is an enumerator that will give you 5 character chunks: 这是一个枚举器,它将为您提供5个字符块:

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

Use it like: 像这样使用它:

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

abcde
fghij
klmno
pqrst
uvwxy
z

Something like this ? 像这样吗?

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

Contents of file data.txt thecatsatonthemat 文件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)

Contents of new_data.txt new_data.txt的内容

theca tsato nthem at

You can do something like this. 你可以做这样的事情。 file1.txt will be the file where the string is retrieved. file1.txt将是在其中检索字符串的文件。 file2.txt will be the file where the split string will be written. file2.txt将是写入分割字符串的文件。

NOTE: This code assumes that the text file (file1.txt) doesn't have white spaces or newlines. 注意:此代码假定文本文件(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()

Let us assume that the contents of file1.txt is thecatsatonthemat . 让我们假设file1.txt的内容是thecatsatonthemat Running that code, file2.txt will now contain theca tsato nthem at . 运行该代码, file2.txt现在将包含theca tsato nthem at

If you have the string in memory and you need the output in memory, use Steven Burnap's answer. 如果内存中有字符串,而内存中需要输出,请使用Steven Burnap的答案。

If you need to read and write files, here is a fast solution which uses little ( O(1) ) memory, and works in Python 2 and 3: 如果您需要读取和写入文件,这是一个快速解决方案,它使用很少的( 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM