Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python – หาคำที่พบบ่อยที่สุด (Most Frequent Word) ใน List of Strings

ภาพรวม

จาก list ของประโยค ให้หาคำที่ออก现บ่อยที่สุดรวมทุกประโยค ใช้ defaultdict นับความถี่

ตัวอย่างโค้ด


from collections import defaultdict

my_list = [
    "python is best for coders",
    "python is fun",
    "python is easy to learn"
]

print("The list is:", my_list)

word_count = defaultdict(int)
for sentence in my_list:
    for word in sentence.split():
        word_count[word] += 1

result = max(word_count, key=word_count.get)
print("The word that has the maximum frequency:", result)

ผลลัพธ์

The list is: ['python is best for coders', 'python is fun', 'python is easy to learn']
The word that has the maximum frequency: python

คำอธิบาย

  • "python" ปรากฏ 3 ครั้ง (ทุกประโยค)
  • "is" ปรากฏ 3 ครั้ง (เท่ากัน แต่ max คืนตัวแรกที่เจอ)
  • คำอื่นๆ ปรากฏ 1 ครั้ง

วิธีที่ทันสมัยกว่า: Counter


from collections import Counter

words = []
for sentence in my_list:
    words.extend(sentence.split())

word_count = Counter(words)
most_common_word, count = word_count.most_common(1)[0]
print(f"{most_common_word}: {count}")

Pandas Approach


import pandas as pd
s = pd.Series(my_list)
words = s.str.split(expand=True).stack()
result = words.value_counts().index[0]

Case Insensitive & Punctuation


import re
from collections import Counter

words = []
for s in my_list:
    words.extend(re.findall(r'\b\w+\b', s.lower()))

print(Counter(words).most_common(1))