含有空格的字词的python regex。

问题描述 投票:0回答:1

问题的例子。

str1 = "ur a sh * tty comment ."

我需要句子中的每一个词,并想替换成... sh * ttysh***tty (将单词内的空格替换为 *)

如果我试一下

for word in s.split():
    print(word)

我得到的是:

ur
a
sh
*
tty
comment
.

sh * tty 现在分成了三个字

  1. sh
  2. *
  3. tty

但我需要的正是这个词 sh * tty 这样我就可以用 * 并使之 sh***tty 终于。

我不能简单地用 *. 我只需要把一个空格换成 * 如果这个空格在任何英文单词里面(典型的错误)。

我也试过。

s = "ur a sh * tty comment ."
makeBad = s.translate ({ord(c): "*" for c in " "})

但我不想把两个单词之间的空格替换掉.

python regex replace split
1个回答
1
投票

你可以使用

import re
str1 = "ur a sh * tty comment ."
nw = r"[]*!@#$%^&()[{};:,./<>?\\|`~=_+-]"
print( re.sub(rf'(\S) {nw} (\S)', r'\1***\2' , str1) )

Python演示.

在这里,模式将看起来像

(\S) []*!@#$%^&()[{};:,./<>?\\|`~=_+-] (\S)

它符合

  • (\S) - 第1组(\1): 任何非空格字符
  • - 空地
  • []*!@#$%^&()[{};:,./<>?\\|`~=_+-] - 一个字符组成的集合。]*!@#$%^&()[{};:,./<>?\|`~=_+-
  • - 一个空格
  • (\S) - 第2组(\2): 任何非空格字符。
© www.soinside.com 2019 - 2024. All rights reserved.