Как разбить по абзацу в python? - PullRequest
0 голосов
/ 08 марта 2020

У меня есть такие тексты:

['\n      2. Materials and Methods\n       2.1. Data Collection and Metadata Annotations\n      \n        We searched the National Center for Biotechnology Information (NCBI) Gene Expression Omnibus (GEO) database [15]']

I wi sh, чтобы разбить строку по абзацу .. имея в виду по крайней мере два \n в строке. Я не уверен, что все случаи \n разделены одинаковым количеством пробелов.

Как я могу определить такое регулярное выражение такого рода \n + несколько пробелов + \n?

Спасибо!

Ответы [ 2 ]

2 голосов
/ 08 марта 2020

Разделить на \n (<em>any amount of spaces</em>) \n затем:

l = re.split(r'\n\s*\n', l)
print (l)

Оставляет пробелы в вводе слева и справа

['\n      2. Materials and Methods\n       2.1. Data Collection and Metadata Annotations',
 '        We searched the National Center for Biotechnology Information (NCBI) Gene Expression Omnibus (GEO) database [15]']

, но об этом позаботится быстрая полоса:

l = [par.strip() for par in re.split(r'\n\s*\n', l)]
print (l)

, поскольку это приводит к

['2. Materials and Methods\n       2.1. Data Collection and Metadata Annotations',
 'We searched the National Center for Biotechnology Information (NCBI) Gene Expression Omnibus (GEO) database [15]']

Бонусный эффект \s* заключается в том, что более 2 последовательных \n с будут рассматриваться как 2 или более, так как выражение по умолчанию захватывает столько, сколько может.

1 голос
/ 08 марта 2020

Может как то так?

>>> a = ['\n      2. Materials and Methods\n       2.1. Data Collection and Metadata Annotations\n      \n        We searched the National Center for Biotechnology Information (NCBI) Gene Expression Omnibus (GEO) database [15]']
>>> output = [i.strip() for i in a[0].split('\n') if i.strip() != '']
>>> output
['2. Materials and Methods', '2.1. Data Collection and Metadata Annotations', 'We searched the National Center for Biotechnology Information (NCBI) Gene Expression Omnibus (GEO) database [15]']
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...