如何在不使用python中的正则表达式的情况下查找并消除连续重复的标点符号?

如何在不使用python中的正则表达式的情况下查找并消除连续重复的标点符号?,python,punctuation,Python,Punctuation,我想去掉重复的连续标点符号,只留下其中一个 如果我有 string='下雨了吗??', 我想去 string='下雨了吗?' 但是我不想摆脱“…” 我还需要在不使用正则表达式的情况下执行此操作。我是python的初学者,如果有任何建议或提示,我将不胜感激。谢谢:)以下方法如何: import string text = 'Is it raining???? No,,,, but...,,,, it is snoooowing!!!!!!!' for punctuation in string

我想去掉重复的连续标点符号,只留下其中一个

如果我有
string='下雨了吗??'
, 我想去
string='下雨了吗?'
但是我不想摆脱
“…”


我还需要在不使用正则表达式的情况下执行此操作。我是python的初学者,如果有任何建议或提示,我将不胜感激。谢谢:)

以下方法如何:

import string

text = 'Is it raining???? No,,,, but...,,,, it is snoooowing!!!!!!!'

for punctuation in string.punctuation:
    if punctuation != '.':
        while True:
            replaced =  text.replace(punctuation * 2, punctuation)
            if replaced == text:
                break
            text = replaced

print(text)
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))
这将产生以下输出:

下雨了吗?不,但是…,它在偷窥!
或者,对于提供相同结果的更高效版本:

import string

text = 'Is it raining???? No,,,, but...,,,, it is snoooowing!!!!!!!'
last = None
output = []

for c in text:
    if c == '.':
        output.append(c)
    elif c != last:
        if c in string.punctuation:
            last = c
        else:
            last = None
        output.append(c)

print(''.join(output))

还有另一种
groupby
方法:

import string

text = 'Is it raining???? No,,,, but...,,,, it is snoooowing!!!!!!!'

for punctuation in string.punctuation:
    if punctuation != '.':
        while True:
            replaced =  text.replace(punctuation * 2, punctuation)
            if replaced == text:
                break
            text = replaced

print(text)
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))
输出

Thisss is ... a test!!! string,,,,, with 1234445556667 rrrrepeats????
Thisss is ... a test! string, with 1234445556667 rrrrepeats?

你想只在问号上这样做吗?你试过什么,它到底有什么问题?为什么你不能使用正则表达式?@taesu不,任何标点符号都可以,除了句点以外?“我不知道从哪里开始,因为我对python的知识非常基础”-那么你还没有准备好在这里提问。考虑下面的一个基本教程来掌握语言。如果<代码> s=“刺客< /代码>”怎么办?另一个测试用例失败了:<代码> A!!b!”使用
字符串。标点符号将非常好。不幸的是,只有当重复模式出现一次时,这才有效。如果字符串中有一个额外的重复位置,代码将删除所有出现的标点符号。你能提供一个不起作用的示例吗?第一个示例使用
while True
确保替换所有模式。该示例显示了正在替换的两组
,,,