Py学习  »  Python

python正则表达式:用特殊字符替换数字

Parsa • 3 年前 • 1518 次点击  

想象一下我有一根像 dslkf 234 dkf23 12asd 2 23 4 . 我想用 <NUM> .

我试过了 re.sub('\s\d+\s', ' <NUM> ', s) 1.我想要 dslkf <NUM> dkf23 12asd <NUM> <NUM> <NUM> 但最终我得到的是: dslkf <NUM> dkf23 12asd <NUM> 23 4

我知道为什么没有替换“4”,因为它后面没有任何空格字符。 但对于另一个,我不知道为什么。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130112
 
1518 次点击  
文章 [ 3 ]  |  最新文章 3 年前
Cubix48
Reply   •   1 楼
Cubix48    3 年前

你不一定需要正则表达式来做这件事,这里有一个 更快 替代使用 split() join() :

data = "dslkf 234 dkf23 12asd 2 23 4"

new_data = " ".join(word if not word.isdigit() else "<NUM>" for word in data.split())
print(new_data)  # dslkf <NUM> dkf23 12asd <NUM> <NUM> <NUM>

  • 我们把句子分成几个单词,每个单词我们都检查它是否是一个数字。如果是这样,我们用 <NUM> .
Parsa
Reply   •   2 楼
Parsa    3 年前

我自己找到了答案。 使用lookback和lookahead非常有用。 最后,我得到了 $ 签名 代码如下所示:

pattern = "(?<=\s)\d+(?=\s|$)"

new_s = re.sub(pattern, '<NUM>', s)

虽然我在发帖前找到了答案,但由于没有找到类似的问题,我还是把这个问题发了出来,供未来的求职者参考。

Tim Biegeleisen
Reply   •   3 楼
Tim Biegeleisen    3 年前

更换 \b\d+\b :

inp = "dslkf 234 dkf23 12asd 2 23 4"
output = re.sub(r'\b\d+\b', r'<NUM>', inp)
print(output)  # dslkf <NUM> dkf23 12asd <NUM> <NUM> <NUM>