关于数组:替换python3中字符串中的整个单词

Replace whole words in strings in python3

本问题已经有最佳答案,请猛点这里访问。

我需要的帮助是只替换一个较长的字符串中的整个单词,它们在字符串中的位置,而被替换的单词也在一个列表中,因此我们循环遍历所有的单词并替换所有的单词。我尝试过使用这个解决方案,但它没有起作用,我还没有找到任何解决这个问题的方法。

我的代码是:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import re

string1="box unbox boxing boxer box box"
string2="ban banana unban ban ban"
string3="box unbox boxing boxer box box ban banana unban ban ban"

dictionary={"box" ,"ban"}

var ="chair"

pat = re.compile(r'\b' + '|'.join(dictionary) + r'\b')

string1 = pat.sub(var, string1)
string2 = pat.sub(var, string2)
string3 = pat.sub(var, string3)

print(string1)
print(string2)
print(string3)

我想用"椅子"代替"盒子"和"禁令"两个词,不管它们在字符串的末尾或开头的位置如何,也不管它周围有多少空格。它应该只替换"box"和"ban"两个词。

目前的输出是:

1
2
3
chair unbox chairing chairer chair chair
chair banana unchair chair chair
chair unbox chairing chairer chair chair chair banana unchair chair chair

我希望输出如下:

1
2
3
chair unbox boxing boxer chair chair
chair banana unban chair chair
chair unbox boxing boxer chair chair chair banana unban chair chair


这可能是你想要的:

1
2
3
4
5
6
7
8
9
10
import re

strings = ["box unbox boxing boxer box box","ban banana unban ban ban","box unbox boxing boxer box box ban banana unban ban ban"]

lst = ["box" ,"ban"]

rx = re.compile(r'\b(?:{})\b'.format("|".join(lst)))

strings = [rx.sub('chair', string) for string in strings]
print(strings)

这就产生了

1
['chair unbox boxing boxer chair chair', 'chair banana unban chair chair', 'chair unbox boxing boxer chair chair chair banana unban chair chair']


你的问题是你的正则表达式是

1
\bbox|ban\b

它应该在哪里

1
\b(box|ban)\b

将相关行更改为

1
pat = re.compile(r'\b(' + '|'.join(dictionary) + r')\b')