我有以下设置:
fword = "don"
comment_true = "Don is bad. Don't eat nails. Carl&Don. Don&Carl. Don, Don."
comment_false = "Don't do this"
replace_with = "[ANONYMISED]"
首先,我想检查fword
是否在comment_true
或comment_false
中。
接下来,我想用 replace_with
替换 fword
。
结果字符串应该是:
comment_true:
“[ANONYMISED] 不好。不要吃指甲。Carl&Don。Don&Carl。[ANONYMISED],[ANONYMISED]。”
comment_false:
“不要这样做”
目前我正在使用的第一个任务:
True if re.search(r'\b%s\b' % fword, comment) else False
对于我正在使用的第二个任务
re.compile(r"\b%s\b" % fword, re.IGNORECASE).sub(replace_with, comment)
但是对于这个问题,它们是不够的,因为像“don't”或 Carl&Don 这样的缩写部分是匹配的。这个问题不是简单的空格检查,因为我只需要转义一些符号。
请参阅此处的示例: https://regexr.com/42bc8
我怎样才能实现这个目标?
最佳答案
尝试正则表达式:(?:^|(?<=\s))don(?=,|\.|\s|\Z)
关于python - 不要替换 python 中包含撇号或 & 的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53102511/