列印某句子中出現剛好 K 次的所有單詞


當需要列印某個句子中剛好出現 K 次的所有單詞時,我們定義一個方法,該方法使用“split”方法、“remove”方法和“count”方法。透過傳入所需引數來呼叫該方法並顯示輸出。

示例

以下是相同的演示

def key_freq_words(my_string, K):
   my_list = list(my_string.split(" "))
   for i in my_list:
      if my_list.count(i) == K:
         print(i)
         my_list.remove(i)

my_string = "hi there how are you, how are u"
K = 2
print("The string is :")
print(my_string)
print"The repeated words with frequency", " are :"
key_freq_words(my_string, K)

輸出

The string is :
hi there how are you, how are u
The repeated words with frequency 2 are :
how
are

說明

  • 定義了一個名為“key_freq_words”的方法,該方法將字串和鍵作為引數。

  • 該字串根據空格進行分割,並被分配給一個列表。

  • 遍歷該列表,如果元素的計數與鍵值相等,則將其顯示在控制檯上。

  • 一旦打印出來,它就會從列表中刪除。

  • 在方法之外,定義了一個字串並顯示在控制檯上。

  • 定義了鍵的值。

  • 透過傳入字串和鍵來呼叫該方法。

  • 輸出顯示在控制檯上。

更新日期: 15-9-2021

310 次瀏覽

開啟您的 職業生涯

完成本課程並獲得認證

開始學習
廣告