如何解决检测标点符号后的空间和标点符号前的空间
我想在标点符号之后检测缺少的空格,并在标点符号之前检测出多余的空格。我试图使用正则表达式来匹配[A-Za-z0-9][?.,:!][A-Z]
和[A-Za-z0-9]\s+[?.,:!]
,但是当将它们应用于字符串None
时,它们都返回Something is in the air tonight.Or is it ?
。
import re
mystring = "Something is in the air tonight.Or is it ?"
missing_space_regex = re.compile('[A-Za-z0-9][?.,:!][A-Z]')
print(missing_space_regex.match(mystring))
extra_space_regex = re.compile('[A-Za-z0-9]\s+[?.,:!]')
print(extra_space_regex.match(mystring))
我意识到上面的extra_space_regex
不会检测到文本以标点符号开头的情况,但是我可以将其作为特殊情况来处理。
解决方法
如果可以使用regex
代替re
,则可以利用正则表达式Unicode字符类,例如\p{P}
作为标点字符:
import regex
mystring = "Something is in the air tonight.Or is it ?"
missing_space_regex = regex.compile(r'.*?\p{P}\S')
print(missing_space_regex.match(mystring))
extra_space_regex = regex.compile(r'.*?\s\p{P}')
print(extra_space_regex.match(mystring))
输出:
<regex.Match object; span=(0,33),match='Something is in the air tonight.O'>
<regex.Match object; span=(0,42),match='Something is in the air tonight.Or is it ?'>
或者,如果您确实要使用所选的标点符号和re
:
punc = "?.,:!"
missing_space_re = re.compile(f".*?[{punc}]\S")
print(missing_space_re.match(mystring))
extra_space_re = re.compile(f'.*?\s[{punc}]')
print(extra_space_re.match(mystring))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。