[英]python regex if some words contain spaces
問題示例:
str1 = "ur a sh * tty comment ."
我需要句子中的每個單詞,並想用sh***tty
替換sh * tty
(用*
替換單詞中的那些空格)
如果我嘗試:
for word in s.split():
print(word)
我得到:
ur
a
sh
*
tty
comment
.
sh * tty
現在被分成 3 個詞
sh
*
tty
但我確實需要這個詞sh * tty
這樣我就可以用*
替換空格並最終使它成為sh***tty
。
我不能簡單地用*
替換空格。 如果該空格在任何英文單詞中(典型錯誤),我只需要用*
替換該空格。
我也試過:
s = "ur a sh * tty comment ."
makeBad = s.translate ({ord(c): "*" for c in " "})
但我不想替換分隔 2 個單詞的空格。
你可以使用
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
):任何非空白字符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.