أفضل الطرق لإزالة علامات الترقيم من النصوص في Python و JavaScript

تم التحديث: ٢٧ مارس ٢٠٢٦

Best Ways to Strip Punctuation From Strings in Python and Javascript

ملخص

Python: استخدم str.translate() مع str.maketrans() من أجل السرعة، أو re.sub() للتحكم في Unicode، أو string.punctuation للبساطة. JavaScript: استخدم .replace() مع التعبير النمطي (regex) /[^\w\s]/g لترميز ASCII، أو Intl.Segmenter لإزالة علامات الترقيم مع مراعاة Unicode. اختر الطريقة بناءً على احتياجات الأداء ونطاق الحروف.

تعد إزالة علامات الترقيم مهمة شائعة في المعالجة المسبقة للغات الطبيعية (NLP)، والتحقق من صحة النماذج، وتحليل النصوص، وتنظيف البيانات. تعتمد الطريقة "الأفضل" على بياناتك (ASCII مقابل Unicode)، ومتطلبات الأداء (السرعة مقابل قابلية القراءة)، وميزات اللغة البرمجية. يقارن هذا الدليل المرجعي بين الطرق في Python و JavaScript مع معايير الأداء والتعامل مع الحالات الخاصة.

Python: الطرق مرتبة حسب السرعة

1. str.translate() + str.maketrans() (الأسرع)

import string

text = "Hello, world! How are you?"
translator = str.maketrans('', '', string.punctuation)
result = text.translate(translator)
print(result)  # "Hello world How are you"

الأداء: الأسرع المميزات: أسرع طريقة في Python الخام، تتعامل مع جميع علامات ترقيم ASCII العيوب: تقتصر على علامات الترقيم المحددة مسبقاً، ولا تزيل علامات ترقيم Unicode

الحالات الخاصة:

# Handles Unicode punctuation from string.punctuation
text = "café…hello"
result = text.translate(translator)
print(result)  # "caféhello" (… removed, é preserved)

# But misses other Unicode punctuation:
text = "Hello «world» and ‹greetings›"  # French quotes
result = text.translate(translator)
print(result)  # "Hello «world» and ‹greetings›" (not removed)

2. التعبيرات النمطية مع re.sub() (الأكثر مرونة)

import re

text = "Hello, world! How are you?"
result = re.sub(r'[^\w\s]', '', text)
print(result)  # "Hello world How are you"

تحليل النمط:

  • [^\w\s] = مطابقة أي شيء ليس حرف كلمة (\w) أو مسافة بيضاء (\s)
  • حروف الكلمة = a-z، A-Z، 0-9، والشرطة السفلية (_)

الأداء: متوسط (أبطأ، ولكن تحكم أكبر) المميزات: يدعم Unicode، أنماط قابلة للتخصيص، يزيل جميع علامات الترقيم العيوب: أبطأ من translate()، ويعتبر مبالغاً فيه لترميز ASCII البسيط

لعلامات ترقيم Unicode:

# Remove all Unicode punctuation (including accents, special chars)
text = "Hello, café! «World»"
result = re.sub(r'[^\w\s]', '', text, flags=re.UNICODE)
print(result)  # "Hello café World"

# Remove punctuation but keep accents:
result = re.sub(r'[^\w\s\u0080-\uFFFF]', '', text)
# Keeps non-ASCII letters (accented chars), removes punctuation

3. مجموعة مخصصة من علامات الترقيم

import string

PUNCTUATION_TO_REMOVE = set(string.punctuation)

def strip_punctuation(text: str) -> str:
    """Remove ASCII punctuation"""
    return ''.join(char for char in text if char not in PUNCTUATION_TO_REMOVE)

text = "Hello, world! How are you?"
result = strip_punctuation(text)
print(result)  # "Hello world How are you"

الأداء: الأبطأ المميزات: مقروءة، قابلة للتخصيص، حتمية العيوب: أبطأ الطرق الثلاث، وتتعامل فقط مع ASCII

قابلة للتخصيص:

# Remove only specific punctuation
REMOVE_ONLY = {',', '!', '?'}

def strip_select(text: str) -> str:
    return ''.join(char for char in text if char not in REMOVE_ONLY)

text = "Hello, world! How are you?"
result = strip_select(text)
print(result)  # "Hello world How are you"

# Keep some punctuation:
text = "Price: $19.99—amazing!"
result = strip_select(text)
print(result)  # "Price: $19.99—amazing" (keeps $ and .)

4. التعامل المعقد مع Unicode (unicodedata)

import unicodedata

def remove_unicode_punctuation(text: str) -> str:
    """Remove Unicode category Punctuation (P*)"""
    return ''.join(
        char for char in text
        if unicodedata.category(char)[0] != 'P'
    )

text = "Hello, world! «Café»…"
result = remove_unicode_punctuation(text)
print(result)  # "Hello world Café"

فئات Unicode:

  • Pc = علامات ترقيم رابطة (الشرطة السفلية)
  • Pd = علامات ترقيم واصلة (-, –, —)
  • Pe = علامات ترقيم غالق (})])
  • Pf = علامات ترقيم نهائية (»)
  • Pi = علامات ترقيم ابتدائية («)
  • Po = علامات ترقيم أخرى (!, ?, .)
  • Ps = علامات ترقيم فاتحة (([{)

المميزات: تتعامل مع أي علامة ترقيم Unicode بشكل صحيح، ومستقلة عن اللغة العيوب: أبطأ طريقة، وتعتبر مبالغاً فيها لترميز ASCII

JavaScript: الطرق مرتبة حسب السرعة

1. التعبيرات النمطية مع replace() (قياسي)

const text = "Hello, world! How are you?";
const result = text.replace(/[^\w\s]/g, '');
console.log(result);  // "Hello world How are you"

النمط:

  • /[^\w\s]/g = إزالة جميع الحروف التي ليست كلمات وليست مسافات
  • علم g = عام (استبدال جميع الحالات)

الأداء: سريع المميزات: سريع، موجز، يتعامل مع معظم الحالات العيوب: لا يتعامل مع علامات ترقيم Unicode بشكل جيد

لـ Unicode:

// ASCII only (keeps Unicode letters, removes punctuation):
const text = "Hello, café! «World»";
const result = text.replace(/[^\w\s]/gu, '');
console.log(result);  // "Hello café World" (u flag = Unicode)

// Remove all non-letter characters:
const result2 = text.replace(/[^\p{Letter}\p{Number}\s]/gu, '');
console.log(result2);  // "Hello café World"

2. replace() مع Unicode Property Escapes (ES2024)

// Remove all Unicode punctuation
const text = "Hello, world! «Café»";
const result = text.replace(/\p{P}/gu, '');
console.log(result);  // "Hello world Café"

خصائص Unicode:

  • \p{P} = أي علامة ترقيم
  • \p{Punctuation} = نفس مفعول \p{P}
  • \p{Pc} = علامات ترقيم رابطة
  • \p{Pd} = علامات ترقيم واصلة
  • \p{Po} = علامات ترقيم أخرى

المميزات: دقيقة، تتعامل مع جميع علامات ترقيم Unicode العيوب: تتطلب دعم متصفح ES2024+

3. وظيفة مخصصة (سهلة القراءة)

function stripPunctuation(text) {
  const punctuation = /[^\w\s]/g;
  return text.replace(punctuation, '');
}

const text = "Hello, world! How are you?";
const result = stripPunctuation(text);
console.log(result);  // "Hello world How are you"

4. إزالة علامات ترقيم محددة فقط

function removeSpecificPunctuation(text, charsToRemove = ",.!?") {
  const pattern = new RegExp(`[${charsToRemove}]`, 'g');
  return text.replace(pattern, '');
}

const text = "Price: $19.99—amazing!";
const result = removeSpecificPunctuation(text, '!?');
console.log(result);  // "Price: $19.99—amazing"

جدول مقارنة الأداء

اللغة الطريقة الأداء دعم Unicode الأفضل لـ
Python translate() الأسرع ASCII فقط السرعة القصوى، بيانات ASCII
Python re.sub() متوسط Unicode كامل المرونة، نصوص Unicode
Python Set comprehension بطيء ASCII فقط سهولة القراءة، قواعد مخصصة
Python unicodedata الأبطأ Unicode كامل التعامل الدقيق مع Unicode
JavaScript replace(/regex/) سريع ASCII/Unicode محدود الاستخدام العام
JavaScript replace(/\p{P}/gu) متوسط Unicode كامل مشاريع ES2024+

حالات استخدام عملية

حالة استخدام 1: المعالجة المسبقة للنصوص في NLP (إزالة جميع علامات الترقيم)

# Python
import re

texts = ["Hello, world!", "Price: $19.99", "Hello…goodbye"]
cleaned = [re.sub(r'[^\w\s]', '', text) for text in texts]
# ["Hello world", "Price 1999", "Helloody"]
// JavaScript
const texts = ["Hello, world!", "Price: $19.99", "Hello…goodbye"];
const cleaned = texts.map(text => text.replace(/[^\w\s]/gu, ''));
// ["Hello world", "Price 1999", "Helloody"]

حالة استخدام 2: الاحتفاظ بالفاصلة العليا (الاختصارات)

import re

def keep_apostrophes(text):
    return re.sub(r"[^\w\s']", '', text)

text = "It's don't valid, isn't it?"
result = keep_apostrophes(text)
print(result)  # "It's don't valid isn't it"
function keepApostrophes(text) {
  return text.replace(/[^\w\s']/gu, '');
}

const text = "It's don't valid, isn't it?";
const result = keepApostrophes(text);
console.log(result);  // "It's don't valid isn't it"

حالة استخدام 3: إزالة علامات الترقيم مع الاحتفاظ بالواصلات (للكلمات الموصولة)

import re

def keep_hyphens(text):
    return re.sub(r"[^\w\s-]", '', text)

text = "well-known, mother-in-law: important!"
result = keep_hyphens(text)
print(result)  # "well-known mother-in-law important"
function keepHyphens(text) {
  return text.replace(/[^\w\s-]/gu, '');
}

const text = "well-known, mother-in-law: important!";
const result = keepHyphens(text);
console.log(result);  // "well-known mother-in-law important"

حالة استخدام 4: إزالة علامات الترقيم باستثناء النقاط (للحفاظ على الجمل)

import re

def keep_periods(text):
    return re.sub(r"[^\w\s.]", '', text)

text = "Hello, world! How are you? I'm fine."
result = keep_periods(text)
print(result)  # "Hello world How are you I'm fine."

الأخطاء الشائعة والحالات الخاصة

الأرقام في علامات الترقيم

import string

# string.punctuation doesn't include numbers
print(string.punctuation)
# Output: !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

# But \w includes digits, so [^\w\s] removes all punctuation except numbers
text = "Price: $19.99!"
result = re.sub(r"[^\w\s]", '', text)
print(result)  # "Price 1999"  (keeps 1999)

result = re.sub(r"[^\d\s]", '', text)
print(result)  # "  1999"  (keep ONLY digits)

الإيموجي والرموز الخاصة

import re

text = "Hello 👋 world! 🌍 How are you? 😊"

# ASCII-only removal:
result = re.sub(r"[^\w\s]", '', text)
print(result)  # "Hello  world  How are you  " (emoji still there in Python 3.12+)

# With Unicode flag:
result = re.sub(r"[^\w\s]", '', text, flags=re.UNICODE)
print(result)  # Still keeps emoji (they're not punctuation)

# Remove emoji and punctuation:
result = re.sub(r"[^\w\s\p{L}]", '', text)  # Won't work, \p not in Python re
# Use unicodedata instead
import unicodedata
result = ''.join(
    c for c in text
    if unicodedata.category(c)[0] not in ('P', 'So')  # Remove Punctuation and Symbols/Other
)
print(result)  # "Hello  world  How are you"

النصوص من اليمين إلى اليسار (العربية، العبرية)

# Python handles RTL correctly in regex
import re

text = "مرحبا, بالعالم! Hello, world!"
result = re.sub(r'[^\w\s]', '', text)
print(result)  # "مرحبا بالعالم Hello world"
// JavaScript also handles RTL with Unicode flag
const text = "مرحبا, بالعالم! Hello, world!";
const result = text.replace(/[^\w\s]/gu, '');
console.log(result);  // "مرحبا بالعالم Hello world"

اختبار الأداء على بياناتك الخاصة

import timeit
import string
import re

text = "Hello, world! " * 100  # 1400 chars

# Method 1: translate
def m1():
    translator = str.maketrans('', '', string.punctuation)
    return text.translate(translator)

# Method 2: regex
def m2():
    return re.sub(r'[^\w\s]', '', text)

# Method 3: set comprehension
def m3():
    return ''.join(c for c in text if c not in string.punctuation)

print("translate():", timeit.timeit(m1, number=10000))
print("re.sub():", timeit.timeit(m2, number=10000))
print("set comprehension:", timeit.timeit(m3, number=10000))
const text = "Hello, world! ".repeat(100);  // 1400 chars

console.time("regex");
for (let i = 0; i < 10000; i++) {
  text.replace(/[^\w\s]/g, '');
}
console.timeEnd("regex");

console.time("regex unicode");
for (let i = 0; i < 10000; i++) {
  text.replace(/[^\w\s]/gu, '');
}
console.timeEnd("regex unicode");

أفضل الممارسات

استخدم str.translate() إذا كنت:

  • تعمل مع نصوص ASCII فقط
  • الأداء أمر بالغ الأهمية (معالجة ملايين السلاسل النصية)
  • تستخدم Python مع string.punctuation القياسي

استخدم re.sub() إذا كنت:

  • تحتاج لدعم علامات ترقيم Unicode
  • تريد مطابقة أنماط مرنة
  • الأداء مقبول (أقل من مليون سلسلة نصية)

استخدم unicodedata إذا كنت:

  • تحتاج لتحكم دقيق في فئات علامات الترقيم
  • تعمل مع نصوص متعددة اللغات تتطلب تعاملاً دقيقاً مع Unicode

JavaScript: استخدم .replace(/[^\w\s]/gu, '') من أجل:

  • المشاريع الحديثة القياسية
  • عندما يكون دعم Unicode مطلوباً
  • كود سهل القراءة وموجز
  • إزالة علامات الترقيم بسيطة من حيث المفهوم ولكنها دقيقة في التنفيذ. بالنسبة لـ ASCII فقط، فإن translate() الخاصة بـ Python لا تُهزم. بالنسبة لـ Unicode، فإن re.sub() مرنة. JavaScript الخاصة بـ .replace() تتعامل مع كليهما باستخدام regex. اختر بناءً على نوع بياناتك، واحتياجات الأداء، وميزات اللغة المتاحة. اختبر على بياناتك الفعلية — تختلف معايير الأداء بشكل كبير بناءً على طول السلسلة النصية وكثافة علامات الترقيم.


نشرة أسبوعية مجانية

ابقَ على مسار النيرد

بريد واحد أسبوعياً — دورات، مقالات معمّقة، أدوات، وتجارب ذكاء اصطناعي.

بدون إزعاج. إلغاء الاشتراك في أي وقت.