我看到很多建议使用Python中的re(正则表达式)或.join函数来删除句子中连续重复的字母,但我想为特定单词设置例外情况。
例如:我想将这个句子 "sentence = 'hello, join this meeting heere using thiis lllink'" 转化为 "hello, join this meeting here using this link"。知道我有一个单词列表,以保留和忽略重复字母检查:"keepWord = ['Hello', 'meeting']"。
以下是两个我发现有用的脚本:
例如:我想将这个句子 "sentence = 'hello, join this meeting heere using thiis lllink'" 转化为 "hello, join this meeting here using this link"。知道我有一个单词列表,以保留和忽略重复字母检查:"keepWord = ['Hello', 'meeting']"。
以下是两个我发现有用的脚本:
Using .join:
import itertools sentence = ''.join(c[0] for c in itertools.groupby(sentence))
Using regex:
import re sentence = re.compile(r'(.)\1{1,}').sub(r'\1', sentence)
我有一个解决方案,但我认为还有更紧凑和高效的方案。 我目前的解决方案是:
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 = ''.join(c[0] for c in itertools.groupby(word))
new_sentence = sentence +" " + new_word
else:
new_sentence = sentence +" " + word
有什么建议吗?
Hellllo
的情况下,你期望得到什么? - Chriselse
下面的字母的第一个出现来解决。 - Aisha