Разбор текста в абзацы с помощью python (проблема цикла) - PullRequest
0 голосов
/ 18 апреля 2019

Я использую API Google Sheets и python для создания разметки HTML из данных, введенных в электронную таблицу.Иногда пользователь вводит длинные блоки текста в одну ячейку, и я надеюсь использовать python для разбора этого на семантические абзацы при появлении новой строки.

Используя str.splitlines() и forloop, я могу заставить его работать концептуально, но печатается первая итерация цикла.

#!/usr/bin/python

#sample text from spreadsheet
text = """Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."""

#break intro text into paragraphs
def pgparse(text):
    #split at every new line
    lines = text.splitlines()
    #wrap lines in p tags
    for i in lines:
        return '<p>'+i+'</p>'

print(pgparse(text))

Результат:

<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.</p>

Ожидаемый результат:

<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.</p>
<p>It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>

Ответы [ 2 ]

3 голосов
/ 18 апреля 2019
return '<p>'+i+'</p>'

Эта строка выходит из функции.Возможно, вы хотите:

def pgparse(text):
    result = []
    #split at every new line
    lines = text.splitlines()
    #wrap lines in p tags
    for i in lines:
        result.append('<p>'+i+'</p>')
    return result
3 голосов
/ 18 апреля 2019

Вы возвращаете только первую строку.Ваша вторая строка никогда не заканчивается.Попробуйте это:

#!/usr/bin/python

#sample text from spreadsheet
text = """Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."""

#break intro text into paragraphs
def pgparse(text):
    #split at every new line
    lines = text.splitlines()
    #wrap lines in p tags
    return "\n".join('<p>'+i+'</p>' for i in lines)

print(pgparse(text))

Использование выражения генератора для переноса строк, а затем присоедините их обратно с помощью \n

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...