Here's a Python function that cleans text by removing all symbols except alphabets (including multilingual characters), commas, periods, hyphens, plus signs, and numbers:
python
import re
def clean_text(text):
"""
Cleans text by keeping only:
- Alphabet characters (including multilingual)
- Numbers (0-9)
- Commas (,), periods (.), hyphens (-), plus signs (+)
- Whitespace
Args:
text (str): Input text to be cleaned
Returns:
str: Cleaned text
"""
# Pattern explanation:
# \p{L} - any kind of letter from any language (requires re.UNICODE)
# 0-9 - numbers
# ,.-+ - allowed punctuation
# \s - whitespace
pattern = r'[^\p{L}0-9,.+\-\s]'
cleaned_text = re.sub(pattern, '', text, flags=re.UNICODE)
return cleaned_text
# Example usage:
sample_text = "Hello, 世界! This is a test - with 123 numbers + some $ymbols @#%^&*()"
print(clean_text(sample_text))
# Output: "Hello, 世界 This is a test - with 123 numbers + some ymbols "
Notes:
The \p{L} Unicode property matches letters from any language (requires re.UNICODE flag)
The pattern [^...] is a negated character class that matches anything NOT in the specified set
The hyphen - is placed at the end of the character class to avoid being interpreted as a range indicator
The function preserves whitespace, but you can remove \s from the pattern if you want to remove whitespace too
For Python versions before 3.7, you might need to use a different approach for Unicode letter matching, as \p{L} wasn't always consistently supported. In that case, you could use:
python
def clean_text_legacy(text):
# This is a less precise alternative for older Python versions
pattern = r'[^a-zA-Z0-9\u00C0-\u017F,.+\-\s]'
return re.sub(pattern, '', text)
This legacy version covers most Latin-based scripts but might miss some non-Latin characters. The first version is preferred for modern Python versions.