读文件到数组由段分隔的Python [英] read file into array seperated by paragraph Python

查看:129
本文介绍了读文件到数组由段分隔的Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件,我想读这个文本文件导入3个不同的数组,数组1和数组2 ARRAY3。第一段被放在ARRAY1,第二段被放置在数组2等。然后第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 seperated by a blank line. any ideas?

推荐答案

这是基本的code我会尝试:

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天全站免登陆