我看到很多建议使用 re (正则表达式)或 python 中的 .join 删除句子中连续重复的字母,但我想对特殊单词有例外。
例如:
我想要这句话>sentence = 'hello, join this meeting heere using thiis lllink'
像这样>'hello, join this meeting here using this link'
知道我有这个单词列表要保留并忽略重复的字母检查:keepWord = ['Hello','meeting']
我发现有用的两个脚本是:
使用.join:
import itertools
sentence = ''.join(c[0] for c in itertools.groupby(sentence))
Run Code Online (Sandbox Code Playgroud)
使用正则表达式:
import re
sentence = re.compile(r'(.)\1{1,}').sub(r'\1', sentence)
Run Code Online (Sandbox Code Playgroud)
我有一个解决方案,但我认为还有一个更紧凑、更高效的解决方案。我现在的解决方案是:
import itertools
sentence = 'hello, join this meeting heere using thiis lllink'
keepWord = ['hello','meeting']
new_sentence = ''
for word in sentence.split():
if word not in keepWord:
new_word = …Run Code Online (Sandbox Code Playgroud)