将文件读取到由段落Python分隔的数组中 [英] read file into array separated by paragraph Python

查看:84
本文介绍了将文件读取到由段落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.

这篇关于将文件读取到由段落Python分隔的数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆