我看到了很多建议,可以使用re(regex)或.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))
使用正则表达式:
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
有什么建议吗
虽然不是特别紧凑,但这里有一个使用regexp的相当简单的示例:函数
subst
将用单个字符替换重复的字符,然后使用re.sub
为找到的每个单词调用该函数这里假设,因为您的示例
keepWord
列表(第一次提到的地方)的标题大小写为Hello
,而文本的小写字母为hello
,所以您希望对列表执行不区分大小写的比较。因此,无论你的句子包含Hello
还是hello
,它都同样有效给出:
您可以匹配
keepWord
列表中的整个单词,并且在其他上下文中仅替换两个或多个相同字母的序列:见Python demo
正则表达式看起来像
见regex demo。如果组1匹配,则返回其值,否则,将返回完全匹配(要保留的单词)
图案细节
\b(?:hello|meeting)\b
-hello
或meeting
用单词边界括起来|
-或([^\W\d_])
-第1组:任何Unicode字母\1+
-对组1值的一个或多个反向引用相关问题 更多 >
编程相关推荐