如果字符重复多次,请删除该单词

2024-10-02 00:40:27 发布

您现在位置:Python中文网/ 问答频道 /正文

如果单词以4个或更多重复字符开头,我想从句子中删除一个单词。你知道吗

eg: 
['aaaaaaa is really good', 'nott something great',
       'ssssssssssssstackoverflow is a great community']

我需要这样的输出: 例如:

['is really good', 'nott something great', 'is a great community']

我试过这样的方法:

^(\S)\1{3,}

它确实会删除那些重复的字符,但不会删除单词。谢谢


Tags: 方法communityis字符单词something句子good
1条回答
网友
1楼 · 发布于 2024-10-02 00:40:27

在模式末尾添加\S*\s

words = ['aaaaaaa is really good', 'nott something great','ssssssssssssstackoverflow is a great community']
newWords = [re.sub(r'^(\S)\1{3,}\S*\s', '', word) for word in words]

输出:

['is really good', 'nott something great', 'is a great community']

如果字符串可能只由一个单词组成,那么将最后的空格设为可选的\s?而不是\s。你知道吗

相关问题 更多 >

    热门问题