Python 用正则表达式替换第 n 个匹配项
Python Substitute nth Match from a Regular Expression
我正在使用以下正则表达式:
(ADJECTIVE|NOUN|VERB)
在下面的句子中找到这三个词:
The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was unaffected by these events.
我正在尝试 运行 一个循环来获取将改变形容词、名词或动词的用户输入:
new = ''
for c, item in enumerate(madlib_regexp.findall(text), 1):
print(type(c))
# get user input
if item[0] == 'A':
replace = input('Enter an ' + item.lower() + ': ')
else:
replace = input('Enter a ' + item.lower() + ': ')
# replace matches with inputs
global new
new = madlib_regexp.sub(replace, text)
我面临的最大困难是使用枚举中的 "c" 值来单独替换我的循环的第 c 个匹配项。例如,"VERB" 将是我的字符串中的第 3 个匹配项,因此我希望当前用户输入仅替换第 3 个匹配项。
您只需提取要替换的值并使用新的 re.sub
调用来替换它:
import re
matches = madly_regexp.findall(text)
for c, item in enumerate(matches, 1):
print(type(c))
# get user input
if item[0] == 'A':
replace = input('Enter an ' + item.lower() + ': ')
else:
replace = input('Enter a ' + item.lower() + ': ')
# replace matches with inputs
text = re.sub(item, replace, text)
我正在使用以下正则表达式:
(ADJECTIVE|NOUN|VERB)
在下面的句子中找到这三个词:
The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was unaffected by these events.
我正在尝试 运行 一个循环来获取将改变形容词、名词或动词的用户输入:
new = ''
for c, item in enumerate(madlib_regexp.findall(text), 1):
print(type(c))
# get user input
if item[0] == 'A':
replace = input('Enter an ' + item.lower() + ': ')
else:
replace = input('Enter a ' + item.lower() + ': ')
# replace matches with inputs
global new
new = madlib_regexp.sub(replace, text)
我面临的最大困难是使用枚举中的 "c" 值来单独替换我的循环的第 c 个匹配项。例如,"VERB" 将是我的字符串中的第 3 个匹配项,因此我希望当前用户输入仅替换第 3 个匹配项。
您只需提取要替换的值并使用新的 re.sub
调用来替换它:
import re
matches = madly_regexp.findall(text)
for c, item in enumerate(matches, 1):
print(type(c))
# get user input
if item[0] == 'A':
replace = input('Enter an ' + item.lower() + ': ')
else:
replace = input('Enter a ' + item.lower() + ': ')
# replace matches with inputs
text = re.sub(item, replace, text)