Python,分割字符串
我有一个很大的文本文件,里面是字符串。我想把每117个字符分成一行,然后把接下来的117个字符放在下一行,依此类推,直到文件结束。
我试过这样做:`s = """我为了清晰起见,已经去掉了字符串""" space = """
""" file = open('testoutput.txt', 'w') while s: print s[:10] output = output + s + """
"""
s = s[10:]
file.write(output) file.close() print "完成"`
但是我遇到了一个问题,最后输出到文件里的内容看起来像这样:` this [SHIFT]r[BACKSPACE]molecule and its descendants would av[BACKSPACE][BACKSPACE]vary because of mutations
T]r[BACKSPACE]molecule and its descendants would av[BACKSPACE][BACKSPACE]vary because of mutations
ACE]molecule and its descendants would av[BACKSPACE][BACKSPACE]vary because of mutations
le and its descendants would av[BACKSPACE][BACKSPACE]vary because of mutations
descendants would av[BACKSPACE][BACKSPACE]vary because of mutations
ts would av[BACKSPACE][BACKSPACE]vary because of mutations
v[BACKSPACE][BACKSPACE]vary because of mutations
E][BACKSPACE]vary because of mutations
CE]vary because of mutations
cause of mutations
utations
`
2 个回答
3
你可以用普通的切片语法来分割一个缓冲区,或者在读取文件的时候直接分割文件。这是第二种方法的一个例子:
with open(r"/path/to/some/file") as input_file:
line = input_file.read(117)
while line:
print len(line)
line = input_file.read(117)
6
这段代码是用来处理一些数据的。它的主要目的是从一个地方获取信息,然后对这些信息进行一些操作,最后把结果返回给你。
首先,代码会连接到一个数据库,这就像打开一个文件夹,里面存放着很多信息。接着,它会查找特定的数据,就像在文件夹里找某一张纸。
找到数据后,代码会对这些数据进行处理,比如进行计算或者格式化。这个过程就像把一堆杂乱的东西整理成一份清晰的报告。
最后,处理完的数据会被返回给你,可能是显示在屏幕上,或者存储到另一个地方,方便你后续使用。
总的来说,这段代码的工作就是从数据库中获取信息,处理这些信息,然后把结果呈现给你。
while s:
print s[:117]
s = s[117:]