Spaces:
Runtime error
Runtime error
Create preprocessing.py
Browse files- modules/preprocessing.py +39 -0
modules/preprocessing.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# modules/preprocessing.py
|
| 2 |
+
|
| 3 |
+
import re
|
| 4 |
+
import nltk
|
| 5 |
+
|
| 6 |
+
# Download stopwords if not already present
|
| 7 |
+
nltk.download("stopwords", quiet=True)
|
| 8 |
+
from nltk.corpus import stopwords
|
| 9 |
+
|
| 10 |
+
STOPWORDS = set(stopwords.words("english"))
|
| 11 |
+
|
| 12 |
+
def clean_text(text: str) -> str:
|
| 13 |
+
"""
|
| 14 |
+
Basic text cleaning:
|
| 15 |
+
- Lowercase
|
| 16 |
+
- Remove URLs, mentions, hashtags
|
| 17 |
+
- Remove numbers, punctuation, and stopwords
|
| 18 |
+
"""
|
| 19 |
+
text = text.lower()
|
| 20 |
+
|
| 21 |
+
# Remove URLs
|
| 22 |
+
text = re.sub(r"http\S+|www\S+|https\S+", "", text)
|
| 23 |
+
|
| 24 |
+
# Remove mentions and hashtags
|
| 25 |
+
text = re.sub(r"@\w+|#\w+", "", text)
|
| 26 |
+
|
| 27 |
+
# Remove numbers and special characters
|
| 28 |
+
text = re.sub(r"[^a-z\s]", "", text)
|
| 29 |
+
|
| 30 |
+
# Remove stopwords
|
| 31 |
+
tokens = [word for word in text.split() if word not in STOPWORDS]
|
| 32 |
+
|
| 33 |
+
return " ".join(tokens)
|
| 34 |
+
|
| 35 |
+
def preprocess_texts(texts: list) -> list:
|
| 36 |
+
"""
|
| 37 |
+
Clean and preprocess a list of texts.
|
| 38 |
+
"""
|
| 39 |
+
return [clean_text(t) for t in texts if t.strip()]
|