将文件读入由段落分隔的数组中 Python
我有一个文本文件,我想将该文本文件读入3个不同的数组,array1、array2和array3。第一段放入 array1,第二段放入 array2,依此类推。然后将第 4 段放入 array1 element2 中,依此类推,段落之间用空行分隔。有什么想法吗?
I have a text file, I want to read this text file into 3 different arrays, array1 array2 and array3. the first paragraph gets put in array1, the second paragraph gets put in array2 and so on. the 4th paragraph will then be put in array1 element2 and so forth, paragraphs are separated by a blank line. any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这是我要尝试的基本代码:
这应该足以让您开始。如果文件中的段落被两个新行分割,那么“\n\n”应该可以解决分割它们的问题。
This is the basic code I would try:
This should be enough to get you started. If the paragraphs in the file are split by two new lines then "\n\n" should do the trick for splitting them.
我知道这个问题很久以前就被问过,但只是提出我的意见,以便在某个时候对其他人有用。
我知道了根据段落分隔符将输入文件拆分为段落的更简单方法(可以是 \n 或空格或其他任何内容),并且您的问题的代码片段如下所示:
执行此命令后,如果您尝试打印 input_[0] 它将显示第一段,input_[1] 将显示第二段,依此类推。因此,它将输入文件中存在的所有段落放入一个列表中,每个列表元素都包含输入文件中的一个段落。
I know this question was asked long before but just putting my inputs so that it will be useful to somebody else at some point of time.
I got to know much easier way to split the input file into paragraphs based on the Paragraph Separator(it can be a \n or a blank space or anything else) and the code snippet for your question is given below :
And after executing this command, if you try to print input_[0] it will show the first paragraph, input_[1] will show the second paragraph and so on. So it is putting all the paragraphs present in the input file into an List with each List element contains a paragraph from the input file.
此代码将搜索两点之间的线:
This code will search for lines between two points:
因为我想炫耀一下:
Because I feel like showing off:
使用切片也可以。
切片内:[开始索引,结束索引,步骤]
Using slices would also work.
Within slice: [start index, end index,step]
绕过切片的更优雅的方法:
只需确保在最终文本中处理 None
More elegant way to bypass slices:
Just make sure you deal with None in final text