บทนำ
การแทนที่คำที่ซ้ำกันในสตริง (ครั้งที่ 2 เป็นต้นไป) ด้วยคำแทนที่จาก dictionary เช่น แทน "Jane" ด้วย "She" ตั้งแต่ครั้งที่ 2 เป็นต้นไป
ตัวอย่างโค้ด
text = 'Jane is the best. Jane loves to cook. Jane and Will cook together'
replace_dict = {'Jane': 'She'}
print("ข้อความเดิม:", text)
words = text.split()
seen = set()
result_words = []
for word in words:
# ตรวจสอบคำหลังตัดเครื่องหมายวรรคตอน
clean_word = word.rstrip('.,')
if clean_word in replace_dict and clean_word in seen:
# แทนที่ แต่เก็บเครื่องหมายวรรคตอนไว้
punct = word[len(clean_word):]
result_words.append(replace_dict[clean_word] + punct)
else:
seen.add(clean_word)
result_words.append(word)
result = ' '.join(result_words)
print("หลังแทนที่:", result)
ผลลัพธ์
ข้อความเดิม: Jane is the best. Jane loves to cook. Jane and Will cook together หลังแทนที่: Jane is the best. She loves to cook. She and Will cook together
คำอธิบาย
split()แยกคำด้วย spacerstrip('.,')ตัดเครื่องหมายวรรคตอนท้ายเพื่อเปรียบเทียบseenset จำคำที่เจอแล้ว- ครั้งแรกเจอ → เก็บไว้, ครั้งต่อไป → แทนที่
- เก็บเครื่องหมายวรรคตอนต่อท้ายคำไว้
วิธี مختصر (ไม่จัดการเครื่องหมายวรรคตอน)
words = text.split() seen = set() result = ' '.join([replace_dict.get(w, w) if w in seen else (seen.add(w) or w) for w in words])