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

หาคำที่ซ้ำกันใน Strings ภายใน Tuple ด้วย Python

บทนำ

การหาคำที่พบในทุก string ภายใน tuple สามารถทำได้โดยแยกคำด้วย split() แปลงเป็น set แล้วใช้ตัวดำเนินการ & (intersection) เพื่อหาคำร่วม

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

my_tuple = ('Hi there', 'Hi Will,', 'Hi', 'Hi there')
print("Tuple:", my_tuple)

# แยกคำในแต่ละ string -> set -> หาส่วนร่วม
words_sets = [set(s.split()) for s in my_tuple]
common_words = set.intersection(*words_sets)

# เรียงและรวมเป็นสตริง
result = ", ".join(sorted(common_words))

print("คำร่วม:", result)

ผลลัพธ์

Tuple: ('Hi there', 'Hi Will,', 'Hi', 'Hi there')
คำร่วม: Hi

คำอธิบาย

  • s.split() แยกคำด้วย whitespace (default)
  • set(s.split()) ทำให้คำในแต่ละ string ไม่ซ้ำ
  • set.intersection(*sets) หาส่วนร่วมของหลาย set พร้อมกัน
  • sorted() เรียงลำดับอักษร, join() รวมเป็นสตริง

หมายเหตุเกี่ยวเครื่องหมายวรรคตอน

ตัวอย่างมี 'Hi Will,' ซึ่ง split() จะได้ 'Will,' (มีคอมม่า) ไม่ใช่ 'Will' หากต้องการลบเครื่องหมายวรรคตอน ควรใช้ regex หรือ str.translate() ก่อน split

เวอร์ชันจัดการเครื่องหมายวรรคตอน

import string

def clean_words(text):
    return set(text.translate(str.maketrans('', '', string.punctuation)).split())

words_sets = [clean_words(s) for s in my_tuple]
common = set.intersection(*words_sets)
print(", ".join(sorted(common)))