Python 用字符替换单词中的数字

Python 用字符替换单词中的数字,python,regex,Python,Regex,我有一个字符串,比如: 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'] 现在我想替换一个单词中的数字,例如 问题1->问题$ a12,1b->a$,$b

我有一个字符串,比如:

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']
现在我想替换一个单词中的数字,例如

  • 问题1
    ->
    问题$
  • a12
    1b
    ->
    a$
    $b
我尝试了
y=[re.sub(r'\w*\d\w*','$',x)来表示x中的w]

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

['$', '$', 'is', 'the', 'number','of', 'a', '$', 'is', 'the', 'number', 'of', 'b']
我想询问是否有正确替换的方法,如果可能的话,将查找和替换合并到一个函数中。

尝试以下方法:

重新导入
s=“问题1:a12是a的数字,1b是b的数字”
pat=重新编译(“[0-9]+”)
印刷品(关于分页,“$”,s))

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

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

Question$: a$ is the number of a, $b is the number of b
在一个步骤中(结果为字符串形式):

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

Question$: a$ is the number of a, $b is the number of b
输出:

['Question$', 'a$', 'is', 'the', 'number', 'of', 'a', '1b', 'is', 'the', 'number', 'of', 'b', '123']
Question$: a$ is the number of a, 1b is the number of b, abc1uvf
['Question$', 'a$', 'is', 'the', 'number', 'of', 'a', '$b', 'is', 'the', 'number', 'of', 'b', '$']
['Question$', 'a$', 'is', 'the', 'number', 'of', 'a', '$b', 'is', 'the', 'number', 'of', 'b', '123']
请注意,
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)
一步:

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)
重新导入
s=“问题1:a12是a的数字,1b是b的数字,123”

y=re.sub(r’(?解释:

  • re.sub
    的第一个参数是要替换的数字

    \d+
    查找代表一个或多个事件的数字,
    +
    数字的一部分

  • 第二个参数使用什么替换模式。在本例中 它的
    “$”

  • 第三个参数接受输入字符串

这可以根据您的需要工作:

import re
s ="Question1: a12 is the number of a, 1b is the number of b"
print(re.sub('\d+', '$', s))
输出:

Question$: a$ is the number of a, $b is the number of b
试试这个:

import re
x = ['Question1', 'a12', 'is', 'the', 'number', 'of', 'a', '1b', 'is', 'the', 'number', 'of', 'b']
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']

是否要替换所有数字?还是仅当数字以字母相邻时?OP required
1b
as
$b
['Question$', 'a$', 'is', 'the', 'number', 'of', 'a', '$b', 'is', 'the', 'number', 'of', 'b']