Замена текста с использованием RegEx
Contents
[
Hide
]
Регулярные выражения позволяют гибко заменять текст на основе шаблонов, а не фиксированных строк. Включив поддержку regex в ‘replace_text_strategy’, вы можете сопоставлять динамичное содержимое, такое как числа, даты или отформатированные строки.
- Создайте PdfContentEditor экземпляр.
- Привяжите входной PDF‑документ.
- Настройте стратегию замены для использования regex.
- Заменить совпадающие шаблоны во всем документе.
- Сохраните обновлённый PDF‑документ.
import aspose.pdf as ap
import aspose.pdf.facades as pdf_facades
import sys
from os import path
sys.path.append(path.join(path.dirname(__file__), ".."))
from config import set_license, initialize_data_dir
def replace_text_regex(infile, outfile):
# Create PdfContentEditor object
content_editor = pdf_facades.PdfContentEditor()
# Bind document to PdfContentEditor
content_editor.bind_pdf(infile)
# Replace text in the whole document
content_editor.replace_text_strategy.replace_scope = (
pdf_facades.ReplaceTextStrategy.Scope.REPLACE_ALL
)
content_editor.replace_text_strategy.is_regular_expression_used = True
content_editor.replace_text(r"\d{4}", "[NUMBER]")
# Save updated document
content_editor.save(outfile)