В следующем вводе я пытаюсь заменить числа и \n
на ''
и ' '
соответственно.
THE SONNETS\n\n 1\n\nFrom fairest creatures we desire increase,\nThat thereby beauty’s rose might never die,\nBut as the riper should by time decease,\nHis
she hies, 1189\nAnd yokes her silver doves; by whose swift aid\nTheir mistress mounted through the empty skies,\nIn her light chariot quickly is convey’d; 1192\n Holding their course to Paphos, where their queen\n Means to immure herself and not be seen.\n'
input_var
читается из файла с содержимым выше.
file_name = 'sample.txt'
file = open(folder+file_name, mode='r', encoding='utf8')
input_var = file.read()
file.close
Скриншот файла прилагается. ![enter image description here](https://i.stack.imgur.com/kzEV2.png)
Данные в файле
THE SONNETS
1
From fairest creatures we desire increase,
That thereby beauty’s rose might never die,
But as the riper should by time decease,
His
she hies, 1189
And yokes her silver doves; by whose swift aid
Their mistress mounted through the empty skies,
In her light chariot quickly is convey’d; 1192
Holding their course to Paphos, where their queen
Means to immure herself and not be seen.
Для идентификации номеров я использовал регулярное выражение [\s]{3,}\d{1,}\\n
(должно быть не менее 3 пробелов перед номером. (см. эту ссылку для проверки регулярных выражений).
Я использую следующий код для замены регулярного выражения и \n
оба, которые я получил из нескольких ответов в стеке потока.
Код 1 -
# Remove the numbers in sonnets and at the end of lines
pattern = {r'[\s]{3,}\d{1,}\\n' : '',
r'\\n' : ' '
}
regex = re.compile('|'.join(map(re.escape, pattern.keys( ))))
output_var = regex.sub(lambda match: pattern[match.group(0)], input_var)
Код 2 -
rep = dict((re.escape(k), v) for k, v in pattern.items())
pattern_test = re.compile("|".join(rep.keys()))
output_var = pattern_test.sub(lambda m: rep[re.escape(m.group(0))], input_var)
Код 3 -
for i, j in pattern.items():
output_var = input_var.replace(i, j)
, где input_var
имеет вышеупомянутый текст. Все три ничего не заменяют.
Я также пытался
pattern = {r'[\s]{3,}\d{1,}\n' : '',
r'\n' : ' '
}
, но он ничего не заменяет.
pattern = {'[\s]{3,}\d{1,}\n' : '',
'\n' : ' '
}
заменяет только \n
и вывод будет выглядеть как
THE SONNETS 1 From fairest creatures we desire increase, That thereby beauty’s rose might never die, But as the riper should by time decease, His
Регулярное выражение не определено в словаре, и я думаю, что оно воспринимается как буквальная строка, а не как регулярное выражение. Как я могу указать регулярное выражение в словарь? Ответы, которые я нашел в stackoverflow, используют строки, а не регулярные выражения sion как ответ, предоставленный для этого вопроса .
Ожидаемый результат -
THE SONNETS From fairest creatures we desire increase, That thereby beauty’s rose might never die, But as the riper should by time decease, His
she hies,And yokes her silver doves; by whose swift aid Their mistress mounted through the empty skies, In her light chariot quickly is convey’d; Holding their course to Paphos, where their queen Means to immure herself and not be seen. '