Py学习  »  Python

当字符串是模式时,python替换单词而不是单词的一部分

Felix Brauer • 6 年前 • 1630 次点击  

我有这样一种文字模式: *_you_don't_* think_you_don't_* you_don't_*_* you_don't_know_your_youth

我想用“我们”来代替“你”,只有当它是一个词时,而不是当它是词的一部分时。

我曾经尝试过使用单词边界函数,但是只有当文本被分隔成单词时才有效,在我的例子中,模式是使用下划线、星号等来形成的。

import re
s = "*_you_don't_* think_you_don't_* you_don't_*_* you_don't_know_your_youth"
re.sub(r'\you\b', 'we', s)

在上面的示例中,我希望单词看起来像这样: *_we_don't_* think_we_don't_* we_don't_*_* we_don't_know_your_youth

有了这些代码,我写下了我无法达到这个结果。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/34998
文章 [ 5 ]  |  最新文章 6 年前
paarandika
Reply   •   1 楼
paarandika    6 年前

我能想到的最简单的方法是将re.sub与backreference groups结合使用。您可以使用以下方法来完成您的任务。

re.sub(r'([_|\s])(?:you)(_)', r"\1we\2", s)

在这里,它是第一组 ([_|\s]) 第二组是 (_) . (?:you) 是非捕获组。在替换字符串中\1和\2指上述组。所以最终你的替换字符串变成 <whatever character before you>we<whatever character after you>

sln
Reply   •   2 楼
sln    6 年前

既然你知道你想要什么,就用你不想要的作为边界条件。

(?<![^\W_])you(?![^\W_])

https://regex101.com/r/z2TDXA/1

Sebastien D
Reply   •   3 楼
Sebastien D    6 年前

.replace()

s = "_you_don't_ think_you_don't_* you_don't__ you_don't_know_your_youth"
string.replace('_you_', '_we_').replace(' you_', ' we_')

产量

“我们不认为我们不知道你的年轻人”

Vipul Bhardwaj Toto
Reply   •   4 楼
Vipul Bhardwaj Toto    6 年前
[a-zA-Z] - Matches anything that is a single character

![a-zA-Z] - Anything that is not a single English character

? - One or zero match of pattern

(?<![a-zA-Z])you(?![a-zA-Z]) - This matches "you" if not preceded and 
not followed by a letter

import re
s = "*_you_don't_* think_you_don't_* you_don't_*_* you_don't_know_your_youth"
print re.sub(r'(?<![a-zA-Z])you(?![a-z-Z])', 'we', s)

*_we_don't_* think_we_don't_* we_don't_*_* we_don't_know_your_youth

Demo

Matt.G
Reply   •   5 楼
Matt.G    6 年前

(?<=\b|_)you(?=\b|_)

Demo