Python 程式,用於從給定句子中刪除所有重複單詞。


給定一個句子。從中刪除所有重複的單詞。

示例

Input: I am a peaceful soul and blissful soul.
Output: I am a peaceful soul and blissful.

演算法

Step 1: Split input sentence separated by space into words.
Step 2: So to get all those strings together first we will join each string in a given list of strings.
Step 3: now create a dictionary using the counter method which will have strings as key and their Frequencies as value.
Step 4: Join each words are unique to form single string.

範例程式碼

from collections import Counter
def remov_duplicates(st):
   st = st.split(" ")
   for i in range(0, len(st)):
      st[i] = "".join(st[i])
      dupli = Counter(st)
      s = " ".join(dupli.keys())
      print ("After removing the sentence is ::>",s)
      # Driver program
   if __name__ == "__main__":
      st = input("Enter the sentence")
remov_duplicates(st)

輸出

Enter the sentence ::> i am a peaceful soul and blissful soul
After removing the sentence is ::> i am a peaceful soul and blissful

更新於:2020 年 6 月 23 日

518 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告