Удаление одиночных апострофов и лишних пробелов с помощью регулярных выражений

Рейтинг: -1Ответов: 1Опубликовано: 23.03.2023

Разбираю тему с регулярными выражениями, но не получается удалить одиночные апострофы и лишние пробелы. Как должно выглядеть правильное регулярное выражение? Вот моя попытка:

import re

def only_words(text):
    text = re.sub(r'''[^A-z\n'" ]''', "", text)
    print(text)

only_words("""
In a village of La Mancha, the na123me of which I have no desire to call to
mind, there lived not!# long since          o245ne " of those gentlem&%*%$en that keep a lance
in the lance-rack, a132n old buckler,4554 ' a lean hack, and a greyhound for
coursing. 
An olla of rath52(*&er more beef than mutton, a salad on most
nights, scraps on Saturdays, lent123ils on Fridays, and a pigeon or so extra
on Sundays, made away with three-quarters of his income.""")

На выходе остаются лишние пробелы и апострофы: введите сюда описание изображения

Ответы

▲ 1

Вариант - находим пробелы после пробела ИЛИ апостроф, окруженный не апострофами (возможно, через пробелы) ИЛИ пробелы, заканчивающиеся концом строки - и заменяем на пустую строку.

import re

def only_words(text):
    text = re.sub(r"(?<= ) +|(?<!')' *(?!')| +$", "", text)
    print(text)

only_words("""
In a village of La Mancha, the na123me of which I have no desire to call to
mind, there lived not!# long since          o245ne " of those gentlem&%*%$en that keep a lance
in the lance-rack, a132n old buckler,4554 ' a lean hack, and a greyhound for
coursing. 
An olla of rath52(*&er more beef than mutton, a salad on most
nights, scraps on Saturdays, lent123ils on Fridays, and a pigeon or so extra
on Sundays, made away with three-quarters of his income.""")
In a village of La Mancha, the na123me of which I have no desire to call to
mind, there lived not!# long since o245ne " of those gentlem&%*%$en that keep a lance
in the lance-rack, a132n old buckler,4554 a lean hack, and a greyhound for
coursing. 
An olla of rath52(*&er more beef than mutton, a salad on most
nights, scraps on Saturdays, lent123ils on Fridays, and a pigeon or so extra
on Sundays, made away with three-quarters of his income.