read file into array separated by paragraph Python

后端 未结 7 957
半阙折子戏
半阙折子戏 2021-02-08 22:11

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 arr

相关标签:
7条回答
  • 2021-02-08 22:44

    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]
    

    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.

    0 讨论(0)
提交回复
热议问题