Python: создать список отдельных текстов из текстового файла, который содержит несколько текстов - PullRequest
0 голосов
/ 30 августа 2018

У меня есть файл .txt, который содержит 4 текста, и я хотел бы создать список, в котором все тексты будут отображаться в новой строке - таким образом, у меня будет 4 объекта в списке. Код должен что-то сказать: читать текст построчно (но добавлять строки в документе), но как только вы доберетесь до «1 документа из x», начните новую строку. Я пробовал следующее, которое не создает то, что я хочу:

with open('testfile.txt') as f:

    myList = f.readlines()

myList = [x.strip() for x in content]

testfile.txt

1 doc of 4

Hello World. 
This is another question


2 doc of 4

This is a new text file. 
Not much in it.

3 doc of 4

This is the third text. 
It contains separate info.

4 doc of 4

The final text. 
A short one.

ожидаемый вывод для myList:

myList=['Hello World. This is another question',

        'This is a new text file. Not much in it.',

        'This is the third text. It contains separate info.',

        'The final text. A short one.']

1 Ответ

0 голосов
/ 30 августа 2018

Конечно.

Примерно так и будет - он будет ужасно падать, если документ не начинается со строки заголовка.

import re

# This will hold each document as a list of lines.
# To begin with, there are no documents.
myList = []

# Define a regular expression to match header lines.
header_line_re = re.compile(r'\d+ doc of \d+')

with open('testfile.txt') as f:
    for line in f:  # For each line...
        line = line.strip()  # Remove leading and trailing whitespace
        if header_line_re.match(line):  # If the line matches the header line regular expression...
            myList.append([])  # Start a new group within `myList`,
            continue  # then skip processing the line further.
        if line:  # If the line is not empty, simply add it to the last group.
            myList[-1].append(line)

# Recompose the lines back to strings (separated by spaces, not newlines).
myList = [' '.join(doc) for doc in myList]

print(myList)

Вывод:

[
    "Hello World. This is another question",
    "This is a new text file. Not much in it.",
    "This is the third text. It contains separate info.",
    "The final text. A short one.",
]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...