![](/img/trans.png)
[英]How to remove characters that repeat more than twice in a row/together in a string using python?
[英]How to remove characters which repeat more than twice in a string?
例如,我想刪除喜歡重復的字符hhhaaappy
到hhaappy
因為h
和a
重復兩次。 我想刪除重復兩次以上的所有字符。 如何在python中快速實現它?
此外,是否有任何python模塊可以糾正這個詞? 喜歡正確的hhhaaappy
happy
?
你可以使用itertools.groupby
:
import itertools
s = "hhhaaappy"
new_s = [(a, list(b)) for a, b in itertools.groupby(s)]
final_s = ''.join(''.join(b[:-1]) if len(b) > 2 else ''.join(b) for a, b in new_s)
輸出:
'hhaappy'
我認為分享這個會很酷。 模塊稱為自動更正 。
它通過使用候選模型 ,通過對單詞執行“簡單編輯”來工作。 例如,它處理“ 刪除 - >刪除字母 ”,“ 轉置 - >交換兩個相鄰字母 ”,“ 替換 - >將一個字母更改為另一個字母 ”,“ 插入 - >添加字母 ”。
因此, hhhaaappy
可能不起作用,但是hhapy
或hhapppy
可以工作。
>>> from autocorrect import spell
>>> spell('hhhaaappy')
'hhhaaappy'
>>> spell('hhapy')
'shapy'
>>> spell('happpy')
'happy'
>>> spell('hhapppy')
'happy'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.