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

หาคำหลัง Bigram ใน Python


ให้ข้อความ (text) และคำสองคำ first, second หาคำ third ที่อยู่ทันทีหลังลำดับ "first second" ในข้อความ

ตัวอย่าง: text = "lina is a good girl she is a good singer", first = "a", second = "good" ผลลัพธ์ = ["girl", "singer"]

ขั้นตอนการแก้ปัญหา

  1. แยกข้อความเป็นลิสต์คำด้วย split(" ")
  2. วนลูป index i จาก 0 ถึง len-3:
    • ถ้า text[i] == first และ text[i+1] == second ให้เพิ่ม text[i+2] เข้าผลลัพธ์
  3. คืนผลลัพธ์

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

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

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

อินพุต

"lina is a good girl she is a good singer" "a" "good"

เอาต์พุต

['girl', 'singer']

วิธีแก้แบบ Pythonic (ใช้ zip)

def findOcurrences(text, first, second):
    words = text.split()
    return [c for a, b, c in zip(words, words[1:], words[2:]) if a == first and b == second]