#!/usr/bin/env python3
"""
Text Cleaning and Normalization Script
This script provides a flexible function to clean and normalize text data.
Common operations include:
- Unicode normalization and diacritic removal
- Lowercasing
- Punctuation removal
- Digit removal
- Extra whitespace normalization
Usage examples are included at the bottom.
Supports processing single strings, lists of strings, or files.
"""
import argparse
import re
import sys
import unicodedata
import string
from typing import Union, List
def clean_text(
text: Union[str, List[str]],
lower: bool = True,
remove_punctuation: bool = True,
remove_digits: bool = True,
remove_extra_whitespace: bool = True,
remove_diacritics: bool = True
) -> Union[str, List[str]]:
"""
Clean and normalize a single string or list of strings.
Args:
text: Input text (str or List[str])
lower: Convert to lowercase
remove_punctuation: Remove punctuation
remove_digits: Remove digits
remove_extra_whitespace: Normalize whitespace to single spaces
remove_diacritics: Remove diacritics (accents, etc.)
Returns:
Cleaned text (str or List[str])
"""
def _clean_single(s: str) -> str:
if not isinstance(s, str):
s = str(s)
# Unicode normalization and diacritic removal (if enabled)
if remove_diacritics:
s = unicodedata.normalize('NFKD', s)
s = ''.join(c for c in s if not unicodedata.combining(c))
# Lowercase
if lower:
s = s.lower()
# Remove punctuation
if remove_punctuation:
translator = str.maketrans('', '', string.punctuation)
s = s.translate(translator)
# Remove digits
if remove_digits:
s = re.sub(r'\d+', '', s)
# Normalize whitespace
if remove_extra_whitespace:
s = re.sub(r'\s+', ' ', s).strip()
return s
if isinstance(text, str):
return _clean_single(text)
elif isinstance(text, list):
return [_clean_single(t) for t in text]
else:
raise ValueError("Input must be str or List[str]")
def process_file(input_file: str, output_file: str = None, **kwargs) -> None:
"""Process all lines in an input file and write cleaned output."""
with open(input_file, 'r', encoding='utf-8') as f:
lines = [line.strip() for line in f.readlines() if line.strip()]
cleaned_lines = clean_text(lines, **kwargs)
output = output_file or f"{input_file}.cleaned"
with open(output, 'w', encoding='utf-8') as f:
for line in cleaned_lines:
f.write(line + '\n')
print(f"Cleaned {len(lines)} lines -> {output}")
def main():
parser = argparse.ArgumentParser(description="Clean and normalize text data")
parser.add_argument('input', nargs='?', help="Input file path (or use stdin)")
parser.add_argument('-o', '--output', help="Output file path")
parser.add_argument('--no-lower', action='store_true', help="Don't lowercase")
parser.add_argument('--no-punct', action='store_true', help="Don't remove punctuation")
parser.add_argument('--no-digits', action='store_true', help="Don't remove digits")
parser.add_argument('--no-ws', action='store_true', help="Don't normalize whitespace")
parser.add_argument('--no-diacritics', action='store_true', help="Don't remove diacritics")
args = parser.parse_args()
# Build kwargs
kwargs = {
'lower': not args.no_lower,
'remove_punctuation': not args.no_punct,
'remove_digits': not args.no_digits,
'remove_extra_whitespace': not args.no_ws,
'remove_diacritics': not args.no_diacritics,
}
if args.input:
process_file(args.input, args.output, **kwargs)
else:
# Read from stdin
text = sys.stdin.read().strip()
cleaned = clean_text(text, **kwargs)
print(cleaned)
# Example usage (standalone)
if __name__ == "__main__":
# Single string
sample1 = "Hello, World! 123 This is a test. Café naïve résumé."
print("Original:", repr(sample1))
print("Cleaned:", clean_text(sample1))
# Output: hello world this is a test cafe naive resume
# List of strings
sample2 = ["Apple!", "Banana 123", "Café."]
print("\nOriginal list:", sample2)
print("Cleaned list:", clean_text(sample2))
# Output: ['apple', 'banana', 'cafe']
# Run as script: python script.py input.txt -o output.txt
main()
Key Features:
Modular functionclean_text() with customizable flags for flexibility.
Unicode handling: Normalizes to NFKD and strips diacritics (e.g., "café" → "cafe").
CLI support: Use python script.py input.txt to process files, or pipe stdin.
Batch processing: Handles lists or files line-by-line.
No external dependencies beyond Python standard library.
Usage Examples:
bash
# Process stdin
echo "Hello, World! Café 123." | python script.py
# Process file
python script.py data.txt -o cleaned.txt --no-lower
# Interactive in Python
import script_module # Save as module
cleaned = script_module.clean_text("Your text here")
This script is production-ready, efficient, and extensible!