lll*_*lll 2 python punctuation
我想去掉重复的连续标点符号,只留下其中一个。
如果有
string = 'Is it raining????',我想得到
string = 'Is it raining?'
但又不想摆脱'...'
我还需要在不使用正则表达式的情况下执行此操作。我是 python 的初学者,希望得到任何建议或提示。谢谢 :)
还有另一种groupby方法:
from itertools import groupby
from string import punctuation
punc = set(punctuation) - set('.')
s = 'Thisss is ... a test!!! string,,,,, with 1234445556667 rrrrepeats????'
print(s)
newtext = []
for k, g in groupby(s):
if k in punc:
newtext.append(k)
else:
newtext.extend(g)
print(''.join(newtext))
Run Code Online (Sandbox Code Playgroud)
输出
Thisss is ... a test!!! string,,,,, with 1234445556667 rrrrepeats????
Thisss is ... a test! string, with 1234445556667 rrrrepeats?
Run Code Online (Sandbox Code Playgroud)