如何在特定文本或行上将文本文件拆分为小多个文件?
我有书的txt文件,其中每章中都有单词“ - 末尾”。我想将每个章节分为不同的文件,例如 -
Chapter001.txt
Chapter002.txt
Chapter003.txt
.
.
.
ChapterNNN.txt
我在Python3中写下了以下代码。
groups = open('input.txt').read()
groups_divided = groups.split('-THE END-\n')
temp = group.split('\n')
我现在要它将其分为不同的文件,并给他们命名“章节”。 另外,我没有得到如何拆分和创建文件并确保其涵盖所有查询的方法。
另外,请告诉我是否有任何简单的方法可以通过任何软件进行操作。
I have txt file of book which have word "-THE END-" at every chapter. I wanted to split each chapter into different file like-
Chapter001.txt
Chapter002.txt
Chapter003.txt
.
.
.
ChapterNNN.txt
I have written following code in python3.
groups = open('input.txt').read()
groups_divided = groups.split('-THE END-\n')
temp = group.split('\n')
I want now it to split it into different files and give them name "Chapter".
Also I am not getting how to split and create files and ensure that it is covered all queries.
Also please tell me if there is any simple method to do it via any software.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以通过一次处理输入文本文件来进行操作,而不是通过简单地迭代并累积其中的每一行,直到遇到“结尾”行:
You could do it by processing the input text file a line at a time instead of reading the whole thing into memory first by simply iterating over and accumulating each line in it until an "end of chapter" line is encountered:
另一种方法是查找每个
“ - 结尾 - ”
的索引,然后使用这些索引创建章节。请参阅以下代码:One other approach is to find indices of each
"-THE END-"
then create chapters using these indices. See the following code: