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

Tìm Từ Sau Bigram (Occurrences After Bigram) Trong Python

Cho văn bản text và 2 từ first, second. Tìm tất cả từ third xuất hiện ngay sau cặp "first second" (bigram). Trả về danh sách các third theo thứ tự xuất hiện.

Ví dụ: text="lina is a good girl she is a good singer", first="a", second="good" → ["girl", "singer"].

Thuật toán

  1. Tách văn bản thành danh sách từ: words = text.split()
  2. Duyệt chỉ số i từ 0 đến len(words) - 3
  3. Nếu words[i] == first và words[i+1] == second: thêm words[i+2] vào kết quả
  4. Trả về kết quả

Ví dụ (Python)

class Solution(object):
    def findOcurrences(self, text, first, second):
        words = text.split()
        res = []
        for i in range(len(words) - 2):
            if words[i] == first and words[i + 1] == second:
                res.append(words[i + 2])
        return res

ob1 = Solution()
print(ob1.findOcurrences("lina is a good girl she is a good singer", "a", "good"))
# ['girl', 'singer']

Cách khác: dùng zip (Pythonic)

def findOcurrences(text, first, second):
    words = text.split()
    return [w3 for w1, w2, w3 in zip(words, words[1:], words[2:])
            if w1 == first and w2 == second]

Độ phức tạp

  • Thời gian: O(n) (n = số từ)
  • Không gian: O(n) (danh sách từ + kết quả)

Đầu vào / Đầu ra

Input:  text = "lina is a good girl she is a good singer"
        first = "a", second = "good"
Output: ['girl', 'singer']