Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 正则表达式:仅替换一个引用_Python_Regex_Matching - Fatal编程技术网

Python 正则表达式:仅替换一个引用

Python 正则表达式:仅替换一个引用,python,regex,matching,Python,Regex,Matching,我试图用正则表达式替换字符串中特定单词的一个实例,其中需要替换的单词至少出现两次。例如,我有以下几点: 这个名词是形容词,与名词完全不同。 到目前为止,我已经: content = 'The NOUN is ADJECTIVE and is completely different from the NOUN.' noun = input('Enter a noun: ') adj = input('Enter an adjective: ') noun_1 = input('Enter

我试图用正则表达式替换字符串中特定单词的一个实例,其中需要替换的单词至少出现两次。例如,我有以下几点:

这个名词是形容词,与名词完全不同。

到目前为止,我已经:

content = 'The NOUN is ADJECTIVE and is completely different from the NOUN.'   

noun = input('Enter a noun: ')
adj = input('Enter an adjective: ')
noun_1 = input('Enter another noun: ')

names_regex_noun = re.compile(r'NOUN')
content = names_regex_noun.sub(noun, content)
names_regex_adj = re.compile(r'ADJECTIVE')
content = names_regex_adj.sub(adj, content)
names_regex_noun_1 = re.compile(r'NOUN')
content = names_regex_noun_1.sub(noun_1, content) 
print(content)

我遇到的问题是,当使用
names\u regex\u noun.sub(noun,content)
时,它正在替换
content
中的
noun
的两个实例。我只想替换第一个实例,而不影响
NOUN
的第二个实例,这样它就可以被
NOUN\u 1
替换

对于这样的简单表达式,您只需与指定的
计数一起使用即可:

>>> content = 'The NOUN is ADJECTIVE and is completely different from the NOUN.'
>>> noun = 'bird'
>>> content.replace('NOUN', noun, 1)
'The bird is ADJECTIVE and is completely different from the NOUN.'
输出:
abc

re.sub(pattern, repl, string, count=0, flags=0)` 

use `count=1`
re.sub(pattern, repl, string, count=0, flags=0)` 

use `count=1`