Theme
Primary Color

حساب أكثر كلمة متكررة في النص بدون استخدام مكتبات

أولا نقوم بجلب النص

# Get Input From User
text = input("Add Your Input Here: ")

نقوم بجلب كل الكلمات الموجودة في النص ووضعها داخل List

# Split The String To Elements Inside List
words = text.split()

نقوم بإنشاء قاموس Dictionary لتخزين الكلمات وعدد تكرارها

# Create Dictionary To Count Number Of Words
word_count = {}

نقوم بعمل Loop على جميع الكلمات الموجودة داخل ال List وإضافة الكلمة داخل القاموس وبجانبها عدد المرات التي تكررت فيها الكلمة, في حالة الكلمة كانت موجودة من قبل سنقوم بزيادة رقم واحد اما لو كانت الكلمة جديدة سنقوم بوضع قيمتها رقم واحد, اقرأ التعليقات في الكود لفهم الفكرة

# Loop On Words
for word in words:

  # If The Word Exists
  if word in word_count:

    # Add 1 To Word Count
    word_count[word] += 1

  # If Word Is New
  else:

    # Set Word Count To 1
    word_count[word] = 1

سيكون القاموس بهذا الشكل في النهاية إذا إستعملنا المدخلات في الكود التالي

# Input -> "Elzero Elzero Web Web Elzero School School School Elzero"
{'Elzero': 4, 'Web': 2, 'School': 3}

إنشاء متغيرات لتخزين البيانات

# Create Variables To Store Results
most_common_word = None
highest_count = 0

الآن نقوم بعمل Loop على القاموس وسنمر على كل كلمة إذا وجدنا عدد مرات تكرارها أكثر من المتغير highest_count سنعتبر أن هذه أكثر كلمة مكررة حتى نرى هناك أكثر منها أم لا ثم نكمل ال Loop لو وجدنا كلمة أكثر منها في التكرار سنضع القيمة في highest_count أما غير ذلك سنعتبر الكلمة السابقة هي أكثر كلمة مكررة وهكذا

# Loop On Dictionary Items
for word, count in word_count.items():
  if count > highest_count:
    most_common_word = word
    highest_count = count

طباعة النتائج

print("Most Common Word", most_common_word)
print("Number Of Repeats", highest_count)

الكود الكامل

# Get Input From User
text = input("Add Your Input Here: ")

# Split The String To Elements Inside List
words = text.split()

# Create Dictionary To Count Number Of Words
word_count = {}

# Loop On Words
for word in words:

  # If The Word Exists
  if word in word_count:

    # Add 1 To Word Count
    word_count[word] += 1

  # If Word Is New
  else:

    # Set Word Count To 1
    word_count[word] = 1

print(word_count)

# Create Variables To Store Results
most_common_word = None
highest_count = 0

# Loop On Dictionary Items
for word, count in word_count.items():
  if count > highest_count:
    most_common_word = word
    highest_count = count

print("Most Common Word", most_common_word)
print("Number Of Repeats", highest_count)
python برمجة تعلم