Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Tìm từ chung giữa các chuỗi trong tuple Python

Khi cần tìm các từ chung (common words) xuất hiện trong tất cả các chuỗi bên trong một tuple, có thể sử dụng split(), set(), toán tử & (giao tập hợp) và join().

split() tách chuỗi thành list từ theo khoảng trắng (mặc định).

set() tạo tập hợp các từ duy nhất.

Toán tử & trên set thực hiện phép giao (intersection).

join() ghép các từ thành chuỗi.

Ví dụ

# Tuple chứa các chuỗi
my_tuple = ('Hi there', 'Hi Will', 'Hi', 'Hi there')
print(f"Tuple: {my_tuple}")

# Tách từng chuỗi thành set từ
word_sets = [set(s.split()) for s in my_tuple]
print(f"\nCác set từ: {word_sets}")

# Tìm giao của tất cả các set
# set1 & set2 & set3 & ...
common_words = set.intersection(*word_sets)
# Hoặc: common_words = word_sets[0] & word_sets[1] & word_sets[2] & word_sets[3]

print(f"Từ chung: {common_words}")

# Ghép thành chuỗi, sắp xếp để output ổn định
result = ', '.join(sorted(common_words))
print(f"\nKết quả: {result}")

Kết quả

Tuple: ('Hi there', 'Hi Will', 'Hi', 'Hi there')

Các set từ: [{'there', 'Hi'}, {'Will', 'Hi'}, {'Hi'}, {'there', 'Hi'}]
Từ chung: {'Hi'}
Kết quả: Hi

Giải thích

  • Mỗi chuỗi trong tuple được split() thành list từ, rồi chuyển thành set để lấy từ duy nhất.
  • set.intersection(*word_sets) tìm giao của tất cả các set (từ xuất hiện ở MỌI chuỗi).
  • Từ 'Hi' xuất hiện trong 4 chuỗi -> là từ chung duy nhất.
  • sorted() sắp xếp để output xác định, join() ghép thành chuỗi.

Xử lý dấu câu (punctuation)

import re

my_tuple = ('Hi, there!', 'Hi Will.', 'Hi?', 'Hi there')
# Dùng regex tách từ, bỏ dấu câu
word_sets = [set(re.findall(r'\b\w+\b', s.lower())) for s in my_tuple]
common = set.intersection(*word_sets)
print(common)  # {'hi'}

Tìm từ chung của ít nhất N chuỗi (không bắt buộc tất cả)

from collections import Counter

my_tuple = ('apple banana', 'banana cherry', 'apple cherry', 'durian')
# Đếm tần suất từ xuất hiện ở bao nhiêu chuỗi
word_in_strings = Counter()
for s in my_tuple:
    word_in_strings.update(set(s.split()))

# Từ xuất hiện trong ít nhất 2 chuỗi
common_2 = [word for word, count in word_in_strings.items() if count >= 2]
print(common_2)  # ['apple', 'banana', 'cherry']

Tìm từ chung giữa HAI tuple chuỗi

tuple1 = ('hello world', 'python code')
tuple2 = ('world python', 'java code')

words1 = set().union(*[set(s.split()) for s in tuple1])
words2 = set().union(*[set(s.split()) for s in tuple2])
common = words1 & words2
print(common)  # {'world', 'python', 'code'}