将文件读取到由段落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?
答
这是我会尝试的基本代码:
This is the basic code I would try:
f = open('data.txt', 'r')
data = f.read()
array1 = []
array2 = []
array3 = []
splat = data.split("\n\n")
for number, paragraph in enumerate(splat, 1):
if number % 3 == 1:
array1 += [paragraph]
elif number % 3 == 2:
array2 += [paragraph]
elif number % 3 == 0:
array3 += [paragraph]
这应该足以让您入门.如果文件中的段落用两行换行,则"\ n \ n"应该可以把它们分开.
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.