如何使用 python 正则表达式删除首字母缩略词中除空格和句点以外的所有非单词字符

问题描述 投票:0回答:2
test_str = "a.. x what! he was a in the U.S.A.F but in the accounts dept?"

我们需要删除所有非单词,除了已经分隔单词的单个空格和首字母缩略词中的句点。

结果应如下所示:

a x What he was in the U.S.A.F but in the accounts dept
.

我试过:用 9 代替可见性

re_result = re.sub(pattern = r"(?<=\W)[\W][\S](?=\W)", repl= '9', string=test_str, count=0, flags=0)

我得到:

a..9 what! he was a in the U.S.A.F but in the accounts dept?

  1. 为什么x被识别为非词或非空格,如何让它寻找非词和非空格。
  2. 如何去除单词边界处的标点符号,添加
    r"(?<=\W)[\W][\S](?=\W)|\b\W\b"
    不起作用。

感谢您的时间和帮助

python regex-lookarounds
2个回答
0
投票

根据你的描述,我相信你需要做的

re.sub(pattern = r"\W{2,}|\W$", repl= ' ', string=test_str).strip()

这将用空格替换长度超过 1 个符号的任何非单词字符序列。如果它不是单词符号,它也会替换最后一个符号。

演示在regex101


0
投票

使用

\S
匹配非空白字符,因此它也将匹配
x
字符。

查看示例数据,您可能会使用:

\W+(?!\S)

说明

  • \W+
    匹配 1 次或多次非单词字符
  • (?!\S)
    负前瞻断言右边的空白边界

正则表达式演示

© www.soinside.com 2019 - 2024. All rights reserved.