首页 > 解决方案 > 如何使用正则表达式替换带有问号的句子

问题描述

我正在尝试编写一些代码将莎士比亚英语翻译成现代英语,但我在使用 re.sub 替换以问号结尾的句子时遇到问题。当我替换句子时,最后会得到 2 个问号。

我试过添加“\?” 和 ”\?” 到替代字符串,但这不起作用。

p = 'Mine eye hath played the painter and hath stelled. Thy beauty form in table of my heart; My body is the frame wherein this held, and perspective it is the painters art. For through the painter must you see his skill, to find where your true image pictured lies; Which in my bosoms shop is hanging still, that hath his windows glazed with thine eyes. Now see what good turns eyes for eyes have done. Have mine eyes have drawn thy shape, and thine for me? Are windows to my breast, where-through the sun delights to peep, to gaze therein on thee; Yet eyes this cunning want to grace their art; They draw but what they see, know not the heart.'
s = 'Have mine eyes have drawn thy shape, and thine for me?'
s2 = re.sub(r'^(.*?(mine.*?){0})mine', r'\1my', s)
p = re.sub(s,s2,p)
print(p)

下面是输出,您会注意到,在我替换的句子末尾有 2 个问号。

Mine eye hath played the painter and hath stelled. Thy beauty form in table of my heart; My body is the frame wherein this held, and perspective it is the painters art. For through the painter must you see his skill, to find where your true image pictured lies; Which in my bosoms shop is hanging still, that hath his windows glazed with thine eyes. Now see what good turns eyes for eyes have done. Have my eyes have drawn thy shape, and thine for me?? Are windows to my breast, where-through the sun delights to peep, to gaze therein on thee; Yet eyes this cunning want to grace their art; They draw but what they see, know not the heart.

标签: regexpython-3.x

解决方案


s字符串用作正则表达式,因此如果尚未完成re.sub(s,...),您必须转义特殊字符。

在这种情况下,不这样做会告诉正则表达式模块搜索 0 或 1 个e字符。输入字符串中不匹配以下内容?,这说明你得到了旧的? 新的?

在这里我会做:

p = re.sub(re.escape(s),s2,p)

(这比:更通用p = re.sub(s.replace("?",r"\?"),s2,p)


推荐阅读