-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpreprocess.py
More file actions
596 lines (477 loc) · 22 KB
/
Copy pathpreprocess.py
File metadata and controls
596 lines (477 loc) · 22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
# preprocess.py - Geliştirilmiş Versiyonu
import os
import pandas as pd
import dateparser
import re
from dataclasses import dataclass
from typing import Optional, Union, List, Dict
import numpy as np
@dataclass
class RatingMap:
"""
RatingMap sınıfı: rating değerlerini sentiment kategorilerine ayırmak için kullanılır.
positive, neutral, negative: tuple veya list ile rating değerleri
"""
positive: tuple
neutral: tuple
negative: tuple
def convert_relative_dates(df: pd.DataFrame, date_col: str, out_col: str = "converted_date") -> pd.DataFrame:
"""
Göreceli tarih ifadelerini (1 gün önce, 6 ay önce vb.) datetime tipine çevirir.
Türkçe ve İngilizce tarih ifadelerini destekler:
- Türkçe: "bir hafta önce", "6 ay önce", "2 yıl önce", "dün", "bugün"
- İngilizce: "a week ago", "6 months ago", "2 years ago", "yesterday", "today"
"""
df = df.copy()
def parse_multilingual_date(date_str):
"""Türkçe ve İngilizce tarih ifadelerini parse eder"""
if pd.isna(date_str):
return None
date_str = str(date_str).lower().strip()
# Türkçe sayı kelimelerini rakama çevir
turkish_numbers = {
'bir': '1', 'iki': '2', 'üç': '3', 'dört': '4', 'beş': '5',
'altı': '6', 'yedi': '7', 'sekiz': '8', 'dokuz': '9', 'on': '10',
'on bir': '11', 'onbir': '11', 'oniki': '12', 'on iki': '12',
'yirmi': '20', 'otuz': '30'
}
# İngilizce sayı kelimelerini rakama çevir
english_numbers = {
'a': '1', 'an': '1', 'one': '1', 'two': '2', 'three': '3', 'four': '4',
'five': '5', 'six': '6', 'seven': '7', 'eight': '8', 'nine': '9',
'ten': '10', 'eleven': '11', 'twelve': '12', 'thirteen': '13',
'fourteen': '14', 'fifteen': '15', 'sixteen': '16', 'seventeen': '17',
'eighteen': '18', 'nineteen': '19', 'twenty': '20', 'thirty': '30',
'forty': '40', 'fifty': '50', 'sixty': '60', 'seventy': '70',
'eighty': '80', 'ninety': '90'
}
# Sayı kelimelerini rakama çevir (önce İngilizce sonra Türkçe - çakışmaları önlemek için)
for en_num, num in english_numbers.items():
# Kelime sınırlarını dikkate al
date_str = re.sub(r'\b' + en_num + r'\b', num, date_str)
for tr_num, num in turkish_numbers.items():
# Kelime sınırlarını dikkate al
date_str = re.sub(r'\b' + tr_num + r'\b', num, date_str)
# Türkçe ve İngilizce zaman birimi çevirileri (sıralama önemli!)
replacements = {
# Türkçe -> İngilizce (uzun kelimeler önce)
'önce': 'ago',
'günü': 'day',
'gün': 'day',
'haftası': 'week',
'hafta': 'week',
'ayı': 'month',
'ay': 'month',
'yılı': 'year',
'yıl': 'year',
'saati': 'hour',
'saat': 'hour',
'dakikası': 'minute',
'dakika': 'minute',
'dün': 'yesterday',
'bugün': 'today',
'geçen': 'last',
# İngilizce çoğul formları tekil yapmak için
'days': 'day',
'weeks': 'week',
'months': 'month',
'years': 'year',
'hours': 'hour',
'minutes': 'minute'
}
# Kelime sınırlarını kullanarak güvenli replacement
for original_word, standard_word in replacements.items():
# Kelime sınırları ile değiştir
pattern = r'\b' + re.escape(original_word) + r'\b'
date_str = re.sub(pattern, standard_word, date_str)
# dateparser ile parse et
try:
parsed_date = dateparser.parse(date_str)
if parsed_date is None:
# Daha gelişmiş pattern matching - hem Türkçe hem İngilizce
patterns = [
# Standart "X time_unit ago" formatı
r'(\d+)\s*(day|week|month|year|hour|minute)s?\s*ago',
# "X time_unit since" formatı
r'(\d+)\s*(day|week|month|year|hour|minute)s?\s*since',
# "X time_unit back" formatı
r'(\d+)\s*(day|week|month|year|hour|minute)s?\s*back',
# "last X time_unit" formatı
r'last\s*(\d+)\s*(day|week|month|year|hour|minute)s?',
# "X time_unit earlier" formatı
r'(\d+)\s*(day|week|month|year|hour|minute)s?\s*earlier',
# "X time_unit before" formatı
r'(\d+)\s*(day|week|month|year|hour|minute)s?\s*before',
# Türkçe özel durumlar için pattern
r'(\d+)\s*(gün|hafta|ay|yıl|saat|dakika)\s*önce',
]
for pattern in patterns:
match = re.search(pattern, date_str)
if match:
amount = int(match.group(1))
unit = match.group(2)
# Türkçe zaman birimlerini İngilizce'ye çevir
unit_mapping = {
'gün': 'day', 'hafta': 'week', 'ay': 'month',
'yıl': 'year', 'saat': 'hour', 'dakika': 'minute'
}
unit = unit_mapping.get(unit, unit)
if unit == 'day':
parsed_date = pd.Timestamp.now() - pd.Timedelta(days=amount)
elif unit == 'week':
parsed_date = pd.Timestamp.now() - pd.Timedelta(weeks=amount)
elif unit == 'month':
parsed_date = pd.Timestamp.now() - pd.DateOffset(months=amount)
elif unit == 'year':
parsed_date = pd.Timestamp.now() - pd.DateOffset(years=amount)
elif unit == 'hour':
parsed_date = pd.Timestamp.now() - pd.Timedelta(hours=amount)
elif unit == 'minute':
parsed_date = pd.Timestamp.now() - pd.Timedelta(minutes=amount)
break
return parsed_date
except Exception:
return None
df[out_col] = df[date_col].apply(parse_multilingual_date)
# Başarısız parse işlemleri için alternatif yöntem
failed_parses = df[out_col].isna()
if failed_parses.any():
print(f"⚠️ {failed_parses.sum()} tarih parse edilemedi, dateparser ile tekrar deneniyor...")
failed_values = df.loc[failed_parses, date_col].apply(
lambda x: dateparser.parse(str(x)) if pd.notna(x) else None
)
# DateTime tipine cast ederek uyarıyı önle
df.loc[failed_parses, out_col] = failed_values.astype('datetime64[ns]')
return df
def map_rating_to_sentiment(df: pd.DataFrame, rating_col: str, mapping: RatingMap, out_col: str = "sentiment") -> pd.DataFrame:
"""
Rating değerlerini sentiment kategorilerine çevirir.
Ayrıca sentiment güven seviyesi de ekler.
"""
if rating_col not in df.columns:
raise ValueError(f"Rating column '{rating_col}' not found in DataFrame.")
df = df.copy()
ratings = pd.to_numeric(df[rating_col], errors='coerce').astype('Int64')
sentiment = pd.Series(index=df.index, dtype="string")
sentiment_confidence = pd.Series(index=df.index, dtype="float64")
# Sentiment mapping
positive_mask = ratings.isin(mapping.positive)
neutral_mask = ratings.isin(mapping.neutral)
negative_mask = ratings.isin(mapping.negative)
sentiment = sentiment.mask(positive_mask, "positive")
sentiment = sentiment.mask(neutral_mask, "neutral")
sentiment = sentiment.mask(negative_mask, "negative")
# Güven seviyesi hesapla (5 puan için %100, diğerleri için daha düşük)
sentiment_confidence.loc[ratings == 5] = 1.0
sentiment_confidence.loc[ratings == 1] = 1.0
sentiment_confidence.loc[ratings == 4] = 0.8
sentiment_confidence.loc[ratings == 2] = 0.8
sentiment_confidence.loc[ratings == 3] = 0.6
df[out_col] = sentiment
df[out_col + "_confidence"] = sentiment_confidence
return df
def bar_counts_by_rating(df: pd.DataFrame, rating_col: str) -> pd.Series:
"""
Her rating değerinin kaç kere tekrarlandığını sayar (1-5 arası).
Yüzde hesaplamaları da ekler.
"""
s = pd.to_numeric(df[rating_col], errors='coerce')
counts = s.value_counts(dropna=False)
index = list(range(1, 6))
out = pd.Series({i: int(counts.get(i, 0)) for i in index})
out.index.name = rating_col
return out
def filter_last_n_days(df: pd.DataFrame, date_col: str, n_days: int, use_max_date_as_today: bool = True) -> pd.DataFrame:
"""
Son n gün içerisindeki verileri filtreler.
Göreceli tarihler dateparser ile datetime'a çevrildikten sonra kullanılır.
"""
# 1. datetime tipine çevir
dt = pd.to_datetime(df[date_col], errors="coerce")
# 2. Eğer tz-aware ise tz-naive yap
if dt.dt.tz is not None:
dt = dt.dt.tz_convert(None)
# 3. DataFrame kopya
df = df.copy()
df[date_col] = dt
# 4. Bitiş tarihi
if use_max_date_as_today and dt.notna().any():
end = dt.max()
else:
end = pd.Timestamp.now()
# 5. Başlangıç tarihi
start = end - pd.Timedelta(days=n_days)
# 6. Filtreleme
mask = dt.between(start, end, inclusive="both")
filtered_df = df[mask]
print(f"📅 Tarih aralığı: {start.strftime('%Y-%m-%d')} - {end.strftime('%Y-%m-%d')}")
print(f"📊 Filtre öncesi: {len(df)} satır, sonrası: {len(filtered_df)} satır")
return filtered_df
def timeseries_by_sentiment(df: pd.DataFrame, date_col: str, sentiment_col: str, time_grain: str = "D") -> pd.DataFrame:
"""
Belirli bir zaman aralığında (daily/weekly/monthly) sentiment sayısını hesaplar.
time_grain seçenekleri:
- 'D': Günlük
- 'W': Haftalık
- 'M': Aylık
- 'Q': Çeyreklik
"""
d = df[[date_col, sentiment_col]].dropna()
if d.empty:
return pd.DataFrame()
d = d.set_index(pd.DatetimeIndex(d[date_col], name=date_col))
# Zaman serisi oluştur
ts = (
d.groupby(sentiment_col)
.resample(time_grain)
.size()
.unstack(0)
.sort_index()
.fillna(0)
.astype(int)
)
# Eksik sütunları ekle
expected_sentiments = ['negative', 'neutral', 'positive']
for sentiment in expected_sentiments:
if sentiment not in ts.columns:
ts[sentiment] = 0
# Sütun sıralaması
ts = ts.reindex(columns=expected_sentiments, fill_value=0)
return ts
def create_monthly_sentiment_table(df: pd.DataFrame, date_col: str, sentiment_col: str) -> pd.DataFrame:
"""
Aylık sentiment tablosu oluşturur - detaylı istatistiklerle birlikte.
"""
d = df[[date_col, sentiment_col, 'score']].dropna()
if d.empty:
return pd.DataFrame()
# Tarihi index yap
d = d.set_index(pd.DatetimeIndex(d[date_col], name=date_col))
# Aylık gruplama
monthly_data = []
for period, group in d.groupby(pd.Grouper(freq='M')):
if len(group) == 0:
continue
month_stats = {
'Ay': period.strftime('%Y-%m'),
'Ay_Adı': period.strftime('%B %Y'),
'Toplam_Yorum': len(group),
}
# Sentiment sayıları
sentiment_counts = group[sentiment_col].value_counts()
month_stats['Positive'] = sentiment_counts.get('positive', 0)
month_stats['Neutral'] = sentiment_counts.get('neutral', 0)
month_stats['Negative'] = sentiment_counts.get('negative', 0)
# Yüzdeler
total = len(group)
month_stats['Positive_Yüzde'] = (month_stats['Positive'] / total * 100) if total > 0 else 0
month_stats['Neutral_Yüzde'] = (month_stats['Neutral'] / total * 100) if total > 0 else 0
month_stats['Negative_Yüzde'] = (month_stats['Negative'] / total * 100) if total > 0 else 0
# Rating istatistikleri
month_stats['Ortalama_Rating'] = group['score'].mean()
month_stats['Medyan_Rating'] = group['score'].median()
month_stats['Min_Rating'] = group['score'].min()
month_stats['Max_Rating'] = group['score'].max()
# Sentiment skoru (-1 ile +1 arası)
pos_ratio = month_stats['Positive'] / total if total > 0 else 0
neg_ratio = month_stats['Negative'] / total if total > 0 else 0
month_stats['Sentiment_Skoru'] = pos_ratio - neg_ratio
# Dominant sentiment
max_sentiment = sentiment_counts.idxmax() if not sentiment_counts.empty else 'neutral'
month_stats['Dominant_Sentiment'] = max_sentiment.title()
monthly_data.append(month_stats)
if not monthly_data:
return pd.DataFrame()
monthly_df = pd.DataFrame(monthly_data)
# Sütun sıralaması
column_order = [
'Ay', 'Ay_Adı', 'Toplam_Yorum',
'Positive', 'Neutral', 'Negative',
'Positive_Yüzde', 'Neutral_Yüzde', 'Negative_Yüzde',
'Ortalama_Rating', 'Medyan_Rating', 'Min_Rating', 'Max_Rating',
'Sentiment_Skoru', 'Dominant_Sentiment'
]
# Mevcut sütunları sırala
existing_cols = [col for col in column_order if col in monthly_df.columns]
monthly_df = monthly_df[existing_cols]
# Sayısal sütunları yuvarlama
numeric_cols = ['Positive_Yüzde', 'Neutral_Yüzde', 'Negative_Yüzde',
'Ortalama_Rating', 'Medyan_Rating', 'Sentiment_Skoru']
for col in numeric_cols:
if col in monthly_df.columns:
monthly_df[col] = monthly_df[col].round(2)
return monthly_df
def calculate_sentiment_metrics(df: pd.DataFrame, sentiment_col: str = "sentiment") -> Dict:
"""
Sentiment metriklerini hesaplar.
"""
if sentiment_col not in df.columns:
return {}
sentiment_counts = df[sentiment_col].value_counts()
total = len(df[df[sentiment_col].notna()])
metrics = {
'total_reviews': total,
'positive_count': sentiment_counts.get('positive', 0),
'neutral_count': sentiment_counts.get('neutral', 0),
'negative_count': sentiment_counts.get('negative', 0),
'positive_ratio': sentiment_counts.get('positive', 0) / total if total > 0 else 0,
'neutral_ratio': sentiment_counts.get('neutral', 0) / total if total > 0 else 0,
'negative_ratio': sentiment_counts.get('negative', 0) / total if total > 0 else 0,
}
# Sentiment skoru hesapla (-1 ile 1 arasında)
metrics['sentiment_score'] = (
metrics['positive_ratio'] - metrics['negative_ratio']
)
return metrics
def analyze_comment_patterns(df: pd.DataFrame, comment_col: str = "comment") -> Dict:
"""
Yorum metinlerindeki kalıpları analiz eder.
"""
if comment_col not in df.columns:
return {}
comments = df[comment_col].dropna().astype(str)
if comments.empty:
return {}
# Yorum uzunluk istatistikleri
lengths = comments.str.len()
# Yaygın kelimeler (Türkçe stop words hariç)
turkish_stopwords = {
'bir', 'bu', 've', 'için', 'da', 'de', 'ile', 'olan', 'var', 'yok',
'çok', 'daha', 'en', 'gibi', 'kadar', 'bana', 'benim', 'onun', 'bunun',
'şu', 'o', 'ben', 'sen', 'biz', 've', 'veya', 'ama', 'fakat', 'ancak'
}
# Tüm yorumları birleştir ve kelimeler ayır
all_text = ' '.join(comments).lower()
words = re.findall(r'\b\w+\b', all_text)
# Stop words'leri filtrele
filtered_words = [word for word in words if word not in turkish_stopwords and len(word) > 2]
from collections import Counter
word_freq = Counter(filtered_words)
patterns = {
'avg_length': lengths.mean(),
'median_length': lengths.median(),
'min_length': lengths.min(),
'max_length': lengths.max(),
'total_words': len(words),
'unique_words': len(set(words)),
'most_common_words': word_freq.most_common(10),
'exclamation_count': sum(comment.count('!') for comment in comments),
'question_count': sum(comment.count('?') for comment in comments),
}
return patterns
def detect_seasonal_patterns(ts: pd.DataFrame) -> Dict:
"""
Zaman serisinde mevsimsel kalıpları tespit eder.
"""
if ts.empty:
return {}
patterns = {}
# Hafta içi/hafta sonu analizi
ts_with_weekday = ts.copy()
ts_with_weekday['weekday'] = ts_with_weekday.index.weekday
ts_with_weekday['is_weekend'] = ts_with_weekday['weekday'] >= 5
if len(ts_with_weekday) > 7: # En az bir hafta veri varsa
weekend_avg = ts_with_weekday[ts_with_weekday['is_weekend']].drop(['weekday', 'is_weekend'], axis=1).mean()
weekday_avg = ts_with_weekday[~ts_with_weekday['is_weekend']].drop(['weekday', 'is_weekend'], axis=1).mean()
patterns['weekend_vs_weekday'] = {
'weekend_avg': weekend_avg.to_dict(),
'weekday_avg': weekday_avg.to_dict()
}
# Aylık trend analizi
if len(ts_with_weekday) > 30: # En az bir ay veri varsa
monthly_trend = ts_with_weekday.drop(['weekday', 'is_weekend'], axis=1).resample('M').sum()
if len(monthly_trend) > 1:
patterns['monthly_trend'] = monthly_trend.to_dict()
return patterns
def create_feature_engineering(df: pd.DataFrame) -> pd.DataFrame:
"""
Veri setine yeni özellikler ekler (feature engineering).
"""
df = df.copy()
# Tarih tabanlı özellikler
if 'converted_date' in df.columns:
dt = pd.to_datetime(df['converted_date'])
df['year'] = dt.dt.year
df['month'] = dt.dt.month
df['day'] = dt.dt.day
df['weekday'] = dt.dt.weekday
df['is_weekend'] = df['weekday'] >= 5
df['quarter'] = dt.dt.quarter
df['week_of_year'] = dt.dt.isocalendar().week
# Yorum tabanlı özellikler
if 'comment' in df.columns:
comments = df['comment'].astype(str)
df['comment_length'] = comments.str.len()
df['word_count'] = comments.str.split().str.len()
df['exclamation_count'] = comments.str.count('!')
df['question_count'] = comments.str.count(r'\?')
df['capital_ratio'] = comments.str.count(r'[A-ZÇĞIİÖŞÜ]') / df['comment_length']
# Duygu belirten kelimeler
positive_words = ['harika', 'mükemmel', 'güzel', 'iyi', 'temiz', 'hızlı', 'kolay']
negative_words = ['kötü', 'berbat', 'yavaş', 'kirli', 'zor', 'problem', 'sorun']
df['positive_word_count'] = comments.str.lower().str.count('|'.join(positive_words))
df['negative_word_count'] = comments.str.lower().str.count('|'.join(negative_words))
df['sentiment_word_ratio'] = (df['positive_word_count'] - df['negative_word_count']) / df['word_count']
# Rating tabanlı özellikler
if 'score' in df.columns:
df['is_extreme_rating'] = df['score'].isin([1, 5])
df['rating_deviation'] = abs(df['score'] - df['score'].mean())
return df
def export_data_quality_report(df: pd.DataFrame, output_path: str = "outputs/data_quality_report.txt"):
"""
Veri kalitesi raporu oluşturur ve kaydeder.
"""
os.makedirs(os.path.dirname(output_path), exist_ok=True)
with open(output_path, 'w', encoding='utf-8') as f:
f.write("VERİ KALİTESİ RAPORU\n")
f.write("=" * 50 + "\n\n")
# Genel bilgiler
f.write(f"Toplam satır sayısı: {len(df)}\n")
f.write(f"Toplam sütun sayısı: {len(df.columns)}\n\n")
# Eksik değer analizi
f.write("EKSİK DEĞER ANALİZİ:\n")
f.write("-" * 30 + "\n")
missing_data = df.isnull().sum()
for col, missing in missing_data.items():
percentage = (missing / len(df)) * 100
f.write(f"{col}: {missing} ({percentage:.1f}%)\n")
# Veri tipleri
f.write(f"\nVERİ TİPLERİ:\n")
f.write("-" * 30 + "\n")
for col in df.columns:
f.write(f"{col}: {df[col].dtype}\n")
# Benzersiz değer sayıları
f.write(f"\nBENZERSİZ DEĞER SAYILARI:\n")
f.write("-" * 30 + "\n")
for col in df.columns:
unique_count = df[col].nunique()
f.write(f"{col}: {unique_count} benzersiz değer\n")
# Potansiyel problemler
f.write(f"\nPOTANSİYEL PROBLEMLER:\n")
f.write("-" * 30 + "\n")
# Yinelenen satırlar
duplicates = df.duplicated().sum()
f.write(f"Yinelenen satırlar: {duplicates}\n")
# Potansiyel aykırı değerler (rating için)
if 'score' in df.columns:
invalid_ratings = df[~df['score'].isin([1, 2, 3, 4, 5])].shape[0]
f.write(f"Geçersiz rating değerleri (1-5 dışında): {invalid_ratings}\n")
f.write(f"\nRapor oluşturulma tarihi: {pd.Timestamp.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
print(f"✅ Veri kalitesi raporu kaydedildi: {output_path}")
# Yeni yardımcı fonksiyonlar
def clean_text_data(df: pd.DataFrame, text_columns: List[str]) -> pd.DataFrame:
"""
Metin sütunlarını temizler ve standartlaştırır.
"""
df = df.copy()
for col in text_columns:
if col in df.columns:
# Boş değerleri temizle
df[col] = df[col].fillna('')
# Ekstra boşlukları temizle
df[col] = df[col].astype(str).str.strip()
# Çoklu boşlukları tek boşluğa çevir
df[col] = df[col].str.replace(r'\s+', ' ', regex=True)
# HTML etiketlerini temizle (varsa)
df[col] = df[col].str.replace(r'<[^>]+>', '', regex=True)
return df