要从python中的字符串中删除所有重复项,我们需要先将字符串用空格分开,以使每个单词都位于数组中。然后,有多种方法可以删除重复项。
我们可以通过以下方式删除重复项:首先将所有单词都转换为小写,然后对其进行排序,最后仅选择唯一的单词。例如,
sent = "Hi my name is John Doe John Doe is my name" # Seperate out each word words = sent.split(" ") # Convert all words to lowercase words = map(lambda x:x.lower(), words) # Sort the words in order words.sort() unique = [] total_words = len(words) i = 0 while i < (total_words - 1): while i < total_words and words[i] == words[i + 1]: i += 1 unique.append(words[i]) i += 1 print(unique)
输出结果
这将给出输出-
['doe', 'hi', 'john', 'is', 'my']