简体   繁体   English

如何从之前删除空格,而不是在python中标点符号之后

[英]How to strip whitespace from before but not after punctuation in python

relative python newbie here. 相对python新手在这里。 I have a text string output from a program I can't modify. 我有一个我无法修改的程序的文本字符串输出。 For discussion lets say: 讨论让我们说:

text = "This text . Is to test . How it works ! Will it! Or won't it ? Hmm ?"

I want to remove the space before the punctuation, but not remove the second space. 我想在标点符号之前删除空格,但不删除第二个空格。 I've been trying to do it with regex, and I know that I can match the instances I want using match='\\s[\\?.!\\"]\\s' as my search term. 我一直试图用正则表达式来做,我知道我可以使用match ='\\ s [\\?。!\\“] \\ s'作为我的搜索词来匹配我想要的实例。

x=re.search('\s[\?\.\!\"]\s',text)

Is there a way with a re.sub to replace the search term with the leading whitespace removed? 是否有一种方法可以使用re.sub替换搜索词并删除前导空格? Any ideas on how to proceed? 关于如何进行的任何想法?

Put a group around the text you want to keep and refer to that group by number in the replacement pattern: 在要保留的文本周围放置一个组,并在替换模式中按编号引用该组:

re.sub(r'\s([?.!"](?:\s|$))', r'\1', text)

Note that I used a r'' raw string to avoid having to use too many backslashes; 请注意,我使用了一个r''原始字符串,以避免使用太多的反斜杠; you didn't need to add quite so many, however. 但是,你不需要添加那么多。

I also adjusted the match for the following space; 我还调整了以下空间的匹配; it now matches either a space or the end of the string. 它现在匹配一个空格或字符串的结尾。

Demo: 演示:

>>> import re
>>> text = "This text . Is to test . How it works ! Will it! Or won't it ? Hmm ?"
>>> re.sub(r'\s([?.!"](?:\s|$))', r'\1', text)
"This text. Is to test. How it works! Will it! Or won't it? Hmm?"

Use re.sub instead of re.search . 使用re.sub而不是re.search

>>> text = "This text . Is to test . How it works ! Will it! Or won't it ? Hmm ?"
>>> re.sub(r'\s+([?.!"])', r'\1', text)
"This text. Is to test. How it works! Will it! Or won't it? Hmm?"

You don't need to escape ? 你不需要逃避? , . . , ! ! , " inside [] becaue special characters lose their meaning inside [] . "内部[]因为特殊字符在[]内失去意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM