【发布时间】:2023-03-03 00:53:02
【问题描述】:
我看到很多建议在 python 中使用 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
有什么建议吗?
【问题讨论】:
-
如果出现
Hellllo,您有什么期望? -
好吧,我的建议中没有处理这种情况,这可以通过忽略
else下第一次出现的字母来解决。
标签: python regex text preprocessor