使用python

时间:2018-01-02 02:52:02

标签: python regex

我正在尝试使用正则表达式来删除连续'?'序列中的空格和/或'!'在一个字符串中。一个例子是“那是什么?? ?? ?? ??? ???!!!!!”应该改为“那是什么?????????? !!! !!!?”。也就是说,我想连接所有'?'和'!'两者之间没有空间。我目前的代码效果不好:

import re
s = "what is that ?? ? ? ?? ??? ? ! ! ! ? !"
s = re.sub("\? +\?", "??", s)
s = re.sub("\? +\!", "?!", s)
s = re.sub("\! +\!", "!!", s)
s = re.sub("\! +\?", "!?", s)

产生'那是什么??? ???????! !?!',显然没有删除某些空格。我的代码出了什么问题以及如何修改它?

3 个答案:

答案 0 :(得分:0)

你只是想在标点符号周围压缩空白,是吗?这样的事情怎么样:

>>> import re
>>> s = "what is that ?? ? ? ?? ??? ? ! ! ! ? !"
>>> 
>>> re.sub('\s*([!?])\s*', r'\1', s)
'what is that??????????!!!?!'

如果你真的对为什么你的方法不起作用感兴趣,那么它与正则表达式如何在字符串中移动有关。当您编写re.sub("\? +\?", "??", s)并在字符串上运行它时,引擎会像这样运行:

s = "what is that ?? ? ? ?? ??? ? ! ! ! ? !"
# first match -----^^^
# internally, we have:
s = "what is that ??? ? ?? ??? ? ! ! ! ? !"
# restart scan here -^
# next match here ----^^^
# internally:
s = "what is that ??? ??? ??? ? ! ! ! ? !"
# restart scan here ---^
# next match here ------^^^

等等。有一些方法可以防止光标在检查匹配时前进(检查正向前瞻)。

答案 1 :(得分:0)

如果你想要@ g.d.d.c说和句子模式相同那么你可以试试这个:

string_="what is that ?? ? ? ?? ??? ? ! ! ! ? !"
string_1=[]
symbols=[]
string_1.append(string_[:string_.index('?')])
symbols.append(string_[string_.index('?'):])
string_1.append("".join(symbols[0].split()))
print("".join(string_1))

输出:

what is that ??????????!!!?!

答案 2 :(得分:0)

我的方法是将字符串拆分为两个,然后使用正则表达式(删除空格)处理问题区域,然后将这些部分连接在一起。

import re s = "what is that ?? ? ? ?? ??? ? ! ! ! ? !" splitted = s.split('that ') # don't forget to add back in 'that' later splitfirst = splitted[0] s = re.sub("\s+", "", splitted[1]) finalstring = splitfirst+'that '+s print(finalstring) 输出:

╭─jc@jc15 ~/.projects/tests ╰─$ python3 string-replace-question-marks.py what is that ??????????!!!?!