gpt4 book ai didi

python - 错误 : nothing to repeat at position 0 using regex in python

转载 作者:行者123 更新时间:2023-12-01 22:48:52 25 4
gpt4 key购买 nike

给定一个截尾字符串和一个截尾元音字符串,返回未经审查的原始字符串。

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

关于python - 错误 : nothing to repeat at position 0 using regex in python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74760720/

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