gpt4 book ai didi

python - 用字符替换单词中的数字

转载 作者:太空宇宙 更新时间:2023-11-03 13:55:42 25 4
gpt4 key购买 nike

我有一个像这样的字符串:

s ="Question1: a12 is the number of a, 1b is the number of b"

使用 x = re.compile('\w+').findall(s)我可以得到

['Question1', 'a12', 'is', 'the', 'number', 'of', 'a', '1b', 'is', 'the', 'number', 'of', 'b']

现在我想替换一个单词中的数字,例如

  • Question1 -> Question$
  • a12 , 1b -> a$ , $b

我试过了 y = [re.sub(r'\w*\d\w*', '$', x) for w in x]

但它返回的是被 $ 替换的整个单词:

['$', '$', 'is', 'the', 'number','of', 'a', '$', 'is', 'the', 'number', 'of', 'b']

想请问有没有办法正确替换,如果可以的话,把查找和替换合并在一个函数里。

最佳答案

您可以调整以下示例以满足您的要求:

如果要替换的数字仅位于单词的末尾:

import re

s = "Question1: a12 is the number of a, 1b is the number of b, 123"
x = re.compile('\w+').findall(s)
y = [re.sub(r'(?<=[a-zA-Z])\d+$', '$', w) for w in x]
print(y)

输出:

['Question$', 'a$', 'is', 'the', 'number', 'of', 'a', '1b', 'is', 'the', 'number', 'of', 'b', '123']

一步中(字符串形式的结果):

import re
s ="Question1: a12 is the number of a, 1b is the number of b, abc1uvf"
pat = re.compile(r'(?<=[a-zA-Z])\d+(?=\W)')
print(re.sub(pat, "$", s))

输出:

Question$: a$ is the number of a, 1b is the number of b, abc1uvf

如果数字可以位于单词中的任何位置,请使用:

import re

s = "Question1: a12 is the number of a, 1b is the number of b, 123"
x = re.compile('\w+').findall(s)
y = [re.sub(r'\d+', '$', w) for w in x]
print(y)

输出:

['Question$', 'a$', 'is', 'the', 'number', 'of', 'a', '$b', 'is', 'the', 'number', 'of', 'b', '$']

请注意,123 被替换为 $,如果这不是您想要的,请使用:

import re

s = "Question1: a12 is the number of a, 1b is the number of b, 123"
x = re.compile('\w+').findall(s)
y = [re.sub(r'(?<=[a-zA-Z])\d+|\d+(?=[a-zA-Z])', '$', w) for w in x]
print(y)

输出:

['Question$', 'a$', 'is', 'the', 'number', 'of', 'a', '$b', 'is', 'the', 'number', 'of', 'b', '123']

一步到位:

import re

s = "Question1: a12 is the number of a, 1b is the number of b, 123"
y = re.sub(r'(?<=[a-zA-Z])\d+|\d+(?=[a-zA-Z])', '$', s)
print(y)

关于python - 用字符替换单词中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56105645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com