在Python中,要删除字符串中不相邻的重复单词,可以采取以下步骤:
示例代码:
sentence = "I I love love programming programming in in Python Python"
word_list = sentence.split()
示例代码:
new_word_list = []
for i in range(len(word_list)):
if i == 0 or i == len(word_list) - 1:
new_word_list.append(word_list[i])
elif word_list[i] != word_list[i-1] and word_list[i] != word_list[i+1]:
new_word_list.append(word_list[i])
示例代码:
new_sentence = " ".join(new_word_list)
完整代码如下:
sentence = "I I love love programming programming in in Python Python"
word_list = sentence.split()
new_word_list = []
for i in range(len(word_list)):
if i == 0 or i == len(word_list) - 1:
new_word_list.append(word_list[i])
elif word_list[i] != word_list[i-1] and word_list[i] != word_list[i+1]:
new_word_list.append(word_list[i])
new_sentence = " ".join(new_word_list)
print(new_sentence)
运行代码后,输出结果为:
I love programming in Python
该方法将删除字符串中所有不相邻的重复单词,保留了每个重复单词的第一次出现。应用场景包括文本处理、数据清洗、自然语言处理等。
腾讯云相关产品和产品介绍链接地址:
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云