Как добавить новую строку после каждого символа, такого как «. [Xxx]» в строке в Python - PullRequest
0 голосов
/ 05 июля 2019

У меня есть следующая строка:

It reported the proportion of the edits made from America was 51% for the Wikipedia, and 25% for the simple Wikipedia.[142] The Wikimedia Foundation hopes to increase the number in the Global South to 37% by 2015.[143]

Я пытаюсь заменить все символы, подобные этому .[xxx], на .[xxx] \n;

х здесь цифры

Я получаю помощь от разных ответов о переполнении стебля; один такой:

Python вставляет разрыв строки в строке после символа "X"

Регулярное выражение: соответствует полной остановке и одному слову в питоне

import re
str = "It reported the proportion of the edits made from America was 51% 
for the Wikipedia, and 25% for the simple Wikipedia.[142] The Wikimedia 
Foundation hopes to increase the number in the Global South to 37% by 
2015.[143] "
x = re.sub("\.\[[0-9]{2,5}\]\s", "\.\[[0-9]{2,5}\]\s\n",str)
print(x)

Ожидаю следующий вывод:

It reported the proportion of the edits made from America was 51% for the Wikipedia, and 25% for the simple Wikipedia.[142]                          
The Wikimedia Foundation hopes to increase the number in the Global South to 37% by 2015.[143]”

Но я получаю:

It reported the proportion of the edits made from America was 51% for the Wikipedia, and 25% for the simple Wikipedia\\.\[[0-9]{2,5}\]\s   The Wikimedia Foundation hopes to increase the number in the Global South to 37% by 2015\\.\[[0-9]{2,5}\]\s

Ответы [ 3 ]

1 голос
/ 05 июля 2019

Вы можете использовать

(\.\[[^][]*\])\s*

и заменить его на \1\n, см. демонстрацию на regex101.com .


Это читается
(
    \.\[   # ".[" literally
    [^][]* # neither "[" nor "]" 0+ times
    \]     # "]" literally
)\s*       # consume whitespaces, eventually
1 голос
/ 05 июля 2019

Используйте findall (), чтобы определить список подходящих шаблонов. Затем вы можете заменить его оригинальной строкой + '\ n'

1 голос
/ 05 июля 2019

Возможно, вы захотите использовать группы захвата и обратные ссылки в re.sub.Вам также не нужно экранировать строку замены ( regex101 ):

import re
s = '''It reported the proportion of the edits made from America was 51% for the Wikipedia, and 25% for the simple Wikipedia.[142] The Wikimedia Foundation hopes to increase the number in the Global South to 37% by 2015.[143] '''
x = re.sub(r'\.\[([0-9]{2,5})\]\s', r'.[\1] \n', s)
print(x)

Отпечатки:

It reported the proportion of the edits made from America was 51% for the Wikipedia, and 25% for the simple Wikipedia.[142] 
The Wikimedia Foundation hopes to increase the number in the Global South to 37% by 2015.[143] 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...