Python 中 Bigram 之後的出現


假設給定一些單詞。這些單詞是 first 和 second,考慮在 "first second third" 形式的文字中出現的情況,此處 second 緊跟在 first 之後,而 third 緊跟在 second 之後。

對於每種此類情況,將 "third" 新增到答案中,並顯示答案。因此,如果文字為 "lina is a good girl she is a good singer",則 first = “a”,second = “good”,答案將是 [girl, singer]

為了解決這個問題,我們將遵循以下步驟:

  • text := 按空格對字串進行拆分
  • res 是一個空列表
  • for i := 0 到 text 的大小 – 1
    • 如果 i + 2 < text 的長度,並且 text[i] = first 並且 text[i + 1] = second,則將 text[i + 2] 追加到 res
  • 返回 res

示例

讓我們看看以下實現來更好地理解該過程:

 即時演示

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']

更新於:28-4-2020

116 次瀏覽

啟動你的 職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.