【问题标题】:Detect missing space after punctuation and space before punctuation检测标点符号后的缺失空格和标点符号前的空格
【发布时间】:2020-08-12 06:14:18
【问题描述】:

我想检测 标点符号之后的缺失空格和 标点符号之前的额外空格。我尝试使用正则表达式来匹配[A-Za-z0-9][?.,:!][A-Z][A-Za-z0-9]\s+[?.,:!],但是当应用于字符串Something is in the air tonight.Or is it ? 时,这两个都返回None

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 不会检测到文本以标点符号开头的情况,但我可以将其作为特殊情况处理。

【问题讨论】:

  • 这不是您的直接问题。但是在第二个打印中,您使用的是第一个正则表达式而不是第二个。
  • @Rashid'Lee'Ibrahim:感谢您指出这一点。已更正。

标签: python-3.x string punctuation


【解决方案1】:

如果您可以使用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))

【讨论】:

  • re 测试 missing_space_re = re.compile(f"[^{punc}]*?[{punc}]\S") 如果在出现问题的标点符号之前存在正确间隔的标点符号,则会失败。例如,"Something is in the. Air tonight.Or is it?" 没有报告任何问题。最后使用 \s 而不是 \S 可以解决此测试中的问题。
  • 嗯..在我的实际测试用例中似乎失败了。
  • @PeterGrill 我不知道为什么我把[^{punc}] 放在那里而不是.。我已经编辑了我的答案。
  • 那是真正的有意文本。我使用配置文件作为剪贴板来保存我经常需要的文本(SE 应该提供一些地方来做到这一点)。将其用于此处发布的有关 TeX 的问题。顺便说一句,更新的版本似乎很好用。谢谢。
猜你喜欢
  • 2021-12-20
  • 1970-01-01
  • 2019-05-09
  • 2011-04-08
  • 1970-01-01
  • 1970-01-01
  • 2016-04-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多