错误:在python中使用正则表达式在位置0没有重复的内容



给定一个经过删节的字符串和一个经过删节的元音字符串,返回原始未删节字符串。

import re
def uncensor(string1, string2):
# Use a regular expression to find all the asterisks in string1
asterisks = re.findall(r'*?', string1)
# Replace each asterisk with the corresponding character from string2
for i, asterisk in enumerate(asterisks):
string1 = re.sub(asterisk, string2[i], string1, count=1)
return string1
uncensor("Wh*r* d*d my v*w*ls g*", "eeioeo") #➞ "Where did my vowels go?"

我得到了以下错误:

error                                     Traceback (most recent call last)
<ipython-input-28-fee597a500f6> in <module>
11   return string1
12 
---> 13 uncensor("Wh*r* d*d my v*w*ls g*", "eeioeo") #➞ "Where did my vowels go?"
6 frames
/usr/lib/python3.8/sre_parse.py in _parse(source, state, verbose, nested, first)
666                 item = None
667             if not item or item[0][0] is AT:
--> 668                 raise source.error("nothing to repeat",
669                                    source.tell() - here + len(this))
670             if item[0][0] in _REPEATCODES:
error: nothing to repeat at position 0

我尝试了模式r'*+*', r'*', r'*+',但我总是得到错误。

uncensor("Wh*r* d*d my v*w*ls g*", "eeioeo")"我的元音去哪儿了?">

您当前的方法有多个问题,函数逻辑和正则表达式的使用。我会做一个正则表达式替换*与回调函数。在回调中,每次出现*,我们可以从替换元音列表中弹出一个元音。

import re
def uncensor(string1, string2):
chars = list(string2)
return re.sub(r'*', lambda m: chars.pop(0), string1)
output = uncensor("Wh*r* d*d my v*w*ls g*", "eeioeo")
print(output)  # Where did my vowels go

这里有几个问题。首先,在搜索模式中使用?是错误的。如果检查结果,您将看到asterisks为:

['', '', '*', '', '*', '', '', '*', '', '', '', '', '', '', '*', '', '*', '', '', '', '', '*', '']

所以应该是r"*"

其次,在您的替换循环中,asterisk是来自字符串的实际匹配,因此您的模式变为*,这是无效的。您可以执行re.escape(asterisk)来转义它。

最后,您甚至不需要这里的re,因为您的所有regex给您的是一个星号列表。整个任务可以用字符串操作完成:

def uncensor(string1, string2):
# Replace each asterisk with the corresponding character from string2
for repl in string2:
string1 = string1.replace('*', repl, 1)
return string1
uncensor("Wh*r* d*d my v*w*ls g*", "eeioeo") #➞ "Where did my vowels go?"

最新更新