رفع ملف من جهازك إلى Colab
مفيد عند بدء العمل على ملفات TXT أو CSV أو Excel.
from google.colab import files uploaded = files.upload()
corpus.csv أو texts.txt.
صفحة عملية جاهزة للمترجمين ومنسقي الكوربس وفرق الترجمة، تضم أهم أكواد تنظيف البيانات النصية قبل التدريب أو الفهرسة أو إنشاء ذاكرات الترجمة أو إعداد ملفات الترجمة الآلية.
ضع الأوامر التالية في أول خلية داخل Colab لتثبيت المكتبات الأساسية:
!pip install pandas spacy sentence-transformers langdetect openpyxl !python -m spacy download en_core_web_sm
import re
import html
import pandas as pd
from langdetect import detect, DetectorFactory
import spacy
from sentence_transformers import SentenceTransformer
from sklearn.metrics.pairwise import cosine_similarity
DetectorFactory.seed = 0
nlp = spacy.load("en_core_web_sm")
model = SentenceTransformer("all-MiniLM-L6-v2")
ملخص سريع للوظائف الأساسية قبل الشرح التفصيلي.
| المرحلة | الوظيفة | المكتبة | الكود المختصر |
|---|---|---|---|
| التجهيز | قراءة ملف UTF-8 | الأساسية | with open('file.txt', 'r', encoding='utf-8') as f: |
| التنظيف | حذف وسوم HTML | re | re.sub(r'<[^>]+>', '', text) |
| التنظيف | فك رموز HTML | html | html.unescape(text) |
| التنظيف | حذف المسافات الزائدة | re | re.sub(r'\s+', ' ', text).strip() |
| التنظيف | حذف الروابط | re | re.sub(r'http\S+|www\.\S+', '', text) |
| التنظيف | حذف الإيميلات | re | re.sub(r'\S+@\S+', '', text) |
| التطبيع | كشف اللغة | langdetect | detect(text) == 'en' |
| التطبيع | إرجاع الكلمات إلى أصلها | spaCy | " ".join([t.lemma_ for t in nlp(text)]) |
| الجودة | حذف الصفوف الفارغة | pandas | df.dropna(subset=['source','target']) |
| الجودة | إزالة التكرار التام | pandas | df.drop_duplicates(subset=['source','target']) |
| الجودة | فلترة طول الجمل | pandas | df[df['source'].str.len().between(3,500)] |
| الدلالة | Embeddings | sentence-transformers | model.encode(sentences) |
| الدلالة | Cosine Similarity | sklearn | cosine_similarity(embeddings) |
| التسليم | تصدير CSV | pandas | df.to_csv('cleaned.csv', index=False, encoding='utf-8') |
كل بطاقة تحتوي على: الوظيفة، الكود، ثم مثال سريع قبل/بعد.
مفيد عند بدء العمل على ملفات TXT أو CSV أو Excel.
from google.colab import files uploaded = files.upload()
corpus.csv أو texts.txt.
هذا أهم خيار لتجنب ظهور النص العربي أو متعدد اللغات بشكل مشوه.
with open('file.txt', 'r', encoding='utf-8') as f:
text = f.read()
print(text[:300])
مرحبا بالعالم أو Hello world، سيُقرأ بشكل صحيح دون مشاكل ترميز.
مثالي لملفات الترجمة الثنائية التي تحتوي أعمدة مثل source و target.
import pandas as pd
df = pd.read_csv('corpus.csv', encoding='utf-8')
df.head()
source و target،
فستتمكن من تنظيف كل عمود لاحقًا.
مفيد عند سحب نصوص من مواقع أو ملفات تحتوي على وسوم مثل p و div و span.
import re text = "<p>Hello <b>world</b></p>" clean_text = re.sub(r'<[^>]+>', '', text) print(clean_text)
<p>Hello <b>world</b></p>Hello world
أفضل من حذفها مباشرة، لأنه يعيد الرمز إلى شكله الطبيعي.
import html text = "Hello world & everyone" clean_text = html.unescape(text) print(clean_text)
Hello world & everyoneHello world & everyone
ضروري جدًا قبل المقارنة أو إزالة التكرار أو التصدير النهائي.
import re text = " This is a test. " clean_text = re.sub(r'\s+', ' ', text).strip() print(clean_text)
__This___is____a___test.__This is a test.
يفيد في ملفات TXT الكبيرة أو النصوص المنسوخة من الويب.
lines = text.splitlines() lines = [line.strip() for line in lines if line.strip()] clean_text = "\n".join(lines)
مفيد إذا كانت البيانات تحتوي على روابط صفحات أو إحالات غير مفيدة للترجمة.
import re text = "Read more at https://example.com or www.site.com" clean_text = re.sub(r'http\S+|www\.\S+', '', text) clean_text = re.sub(r'\s+', ' ', clean_text).strip() print(clean_text)
Read more at orمفيد لحماية الخصوصية أو حذف البيانات الشخصية من الكوربس.
import re text = "Contact us at info@example.com for details." clean_text = re.sub(r'\S+@\S+', '', text) clean_text = re.sub(r'\s+', ' ', clean_text).strip() print(clean_text)
Contact us at for details.
هذا مهم جدًا لأن بعض الملفات تحتوي على أحرف خفية تؤثر على المطابقة والتجزئة.
import re text = "Hello\u200b world\ufeff" clean_text = re.sub(r'[\u200b-\u200f\ufeff]', '', text) print(clean_text)
يفيد عند نسخ النصوص من Word أو صفحات ويب.
text = text.replace("“", '"').replace("”", '"')
text = text.replace("‘", "'").replace("’", "'")
text = text.replace("—", "-").replace("–", "-")
“Hello”—test إلى "Hello"-test.
إذا كنت تعمل على ملف إنجليزي فقط أو عربي فقط، فهذا الكود مفيد جدًا.
from langdetect import detect
text = "This is a sample sentence."
if detect(text) == 'en':
print("النص إنجليزي")
else:
print("النص ليس إنجليزيًا")
en.
يساعد في تقليل اختلاف الصيغ مثل running و ran و runs.
doc = nlp("The children are running quickly.")
lemmas = " ".join([token.lemma_ for token in doc if not token.is_stop])
print(lemmas)
child run quicklyاختياري، ومفيد عند جمع نصوص عربية من مصادر مختلفة.
import re
def normalize_arabic(text):
text = re.sub(r'[إأآٱ]', 'ا', text)
text = re.sub(r'ى', 'ي', text)
text = re.sub(r'ـ', '', text)
text = re.sub(r'[\u064B-\u065F]', '', text)
return text
text = "إِنَّ اللُّغَةَ العَرَبِيَّةَ جَمِيلَةٌ"
print(normalize_arabic(text))
ان اللغه العربيه جميلههذه المرحلة مهمة جدًا للمترجمين الذين يعملون على كوربس متوازٍ أو ذاكرات ترجمة أو تدريب نماذج ترجمة آلية.
df = df.dropna(subset=['source', 'target'])
df = df[
(df['source'].astype(str).str.strip() != '') &
(df['target'].astype(str).str.strip() != '')
]
def clean_text(text):
text = str(text)
text = html.unescape(text)
text = re.sub(r'<[^>]+>', '', text)
text = re.sub(r'http\S+|www\.\S+', '', text)
text = re.sub(r'\S+@\S+', '', text)
text = re.sub(r'[\u200b-\u200f\ufeff]', '', text)
text = re.sub(r'\s+', ' ', text).strip()
return text
df['source'] = df['source'].apply(clean_text)
df['target'] = df['target'].apply(clean_text)
df = df.drop_duplicates(subset=['source', 'target'])
مفيد عندما يختلف النص فقط في المسافات أو حالة الأحرف.
df['source_norm'] = df['source'].str.lower().str.replace(r'\s+', ' ', regex=True).str.strip() df['target_norm'] = df['target'].str.lower().str.replace(r'\s+', ' ', regex=True).str.strip() df = df.drop_duplicates(subset=['source_norm', 'target_norm']) df = df.drop(columns=['source_norm', 'target_norm'])
Hello World و hello world
سيُعتبران تكرارًا.
مفيد لتحسين جودة التدريب أو إعداد corpus أنظف.
df = df[df['source'].str.len().between(3, 500)] df = df[df['target'].str.len().between(3, 500)]
مهمة لاكتشاف الصفوف المشوهة أو المحاذاة الخاطئة بين الجمل.
src_len = df['source'].str.len() tgt_len = df['target'].str.len() ratio = src_len / tgt_len.replace(0, 1) df = df[ratio.between(0.3, 3.0)]
مهم جدًا في النصوص البرمجية أو التجارية مثل: {name} أو %s.
import re
def count_placeholders(text):
text = str(text)
patterns = re.findall(r'(\{[^}]+\}|%s|%d)', text)
return len(patterns)
df['src_ph'] = df['source'].apply(count_placeholders)
df['tgt_ph'] = df['target'].apply(count_placeholders)
df = df[df['src_ph'] == df['tgt_ph']]
df = df.drop(columns=['src_ph', 'tgt_ph'])
Hello {name}{name} أو placeholder مماثل.
مفيد إذا كنت تريد التأكد أن عمود المصدر إنجليزي والهدف عربي مثلًا.
def safe_detect(text):
try:
return detect(str(text))
except:
return "unknown"
df['source_lang'] = df['source'].apply(safe_detect)
df['target_lang'] = df['target'].apply(safe_detect)
df = df[(df['source_lang'] == 'en') & (df['target_lang'] == 'ar')]
هذه الخطوة متقدمة، لكنها ممتازة عندما تكون الجمل مختلفة قليلًا في الصياغة لكنها متشابهة في المعنى.
يصلح لاكتشاف الجمل القريبة من بعضها دلاليًا، مثل:
How are you? و How do you do?
sentences = [
"How are you?",
"How do you do?",
"The weather is great today.",
"Today the weather is wonderful."
]
embeddings = model.encode(sentences)
sim = cosine_similarity(embeddings)
print(sim)
0.85 أو 0.90 غالبًا تشير إلى تشابه قوي، لكن العتبة تختلف حسب نوع البيانات.
sentences = df['source'].tolist()
embeddings = model.encode(sentences, show_progress_bar=True)
sim_matrix = cosine_similarity(embeddings)
to_drop = set()
threshold = 0.90
for i in range(len(sentences)):
for j in range(i + 1, len(sentences)):
if sim_matrix[i][j] >= threshold:
to_drop.add(j)
df = df.drop(df.index[list(to_drop)]).reset_index(drop=True)
0.85 أو 0.90 أو 0.92.
هذا المثال يجمع أهم ما سبق في دالة واحدة.
import re
import html
sample = """
<p>Hello world!</p>
Visit https://example.com
Email: info@example.com
"""
def clean_text(text):
text = html.unescape(text)
text = re.sub(r'<[^>]+>', '', text)
text = re.sub(r'http\S+|www\.\S+', '', text)
text = re.sub(r'\S+@\S+', '', text)
text = re.sub(r'[\u200b-\u200f\ufeff]', '', text)
text = re.sub(r'\s+', ' ', text).strip()
return text
cleaned = clean_text(sample)
print(cleaned)
Hello world! Visit Email:بعد اكتمال التنظيف، يمكنك حفظ البيانات بعدة صيغ.
df.to_csv('cleaned.csv', index=False, encoding='utf-8')
df.to_excel('cleaned.xlsx', index=False)
with open('cleaned_source.txt', 'w', encoding='utf-8') as f:
for line in df['source']:
f.write(str(line) + '\n')
from google.colab import files
files.download('cleaned.csv')
الأداة الأقوى لتنظيف الضوضاء البصرية مثل HTML والروابط والمسافات والأحرف غير المرغوبة بسرعة ومرونة.
يقدم تطبيعًا لغويًا مفيدًا عبر Lemmatization، مما يقلل اختلاف الصيغ الصرفية عند المقارنة والتحليل.
مثالي لملفات الترجمة الثنائية والجداول، ويجعل حذف التكرار والصفوف الفارغة والتصدير أمرًا سهلًا جدًا.
يفهم المعنى لا الشكل فقط، لذلك يساعد على اكتشاف التكرارات القريبة دلاليًا التي لا تراها الأدوات التقليدية.