🛠️ToolsShed

Text Redactor

Redact sensitive words or phrases from text with customizable replacement styles.

Separate words or phrases with commas.

Replace with:

常见问题

代码实现

import re

def redact_text(text, words, replacement="[REDACTED]", case_sensitive=False, whole_word=True):
    for word in words:
        escaped = re.escape(word)
        pattern = rf"\b{escaped}\b" if whole_word else escaped
        flags = 0 if case_sensitive else re.IGNORECASE
        text = re.sub(pattern, lambda m: replacement, text, flags=flags)
    return text

text = "John Smith at john.doe@example.com called from 555-1234."
words = ["John", "Smith", "john.doe@example.com", "555-1234"]
print(redact_text(text, words))
# [REDACTED] [REDACTED] at [REDACTED] called from [REDACTED].

# With block replacement
print(redact_text(text, words, replacement="█████"))

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.