删除单词中的重复字符 [英] Remove repeating characters from words
问题描述
我想知道将"haaaaapppppyyyy"转换为"haappyy"的最佳方法是什么.
I was wondering what is the best way to convert something like "haaaaapppppyyy" to "haappyy".
基本上,在解析语时,人们有时会重复字符以增加重点.
Basically, when parsing slang, people sometimes repeat characters for added emphasis.
我想知道这样做的最好方法是什么?使用set()
无效,因为字母的顺序显然很重要.
I was wondering what the best way to do this is? Using set()
doesn't work because the order of the letters is obviously important.
有什么想法吗?我正在使用Python + nltk.
Any ideas? I'm using Python + nltk.
推荐答案
可以使用正则表达式完成:
It can be done using regular expressions:
>>> import re
>>> re.sub(r'(.)\1+', r'\1\1', "haaaaapppppyyy")
'haappyy'
(.)\1+
将任何字符(.
)后面跟一个或多个相同字符(由于backref \1
必须相同)补充两倍字符.
(.)\1+
repleaces any character (.
) followed by one or more of the same character (because of the backref \1
it must be the same) by twice the character.
这篇关于删除单词中的重复字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!