最新消息:20210917 已从crifan.com换到crifan.org

【已解决】Python中re.sub出错:sre_constants.error bogus escape end of line

Python crifan 3175浏览 0评论

对于:

英语资源\Dr. Seuss The Big Red Book of Beginner Books\音频\01 I Want to Be Somebody New!.mp3

的字符串,想要把:

英语资源\

换成:

英语资源\storybook\

然后去用:

StorybookPathPrefix = "storybook"

unifiedAudioFilePath = re.sub("英语资源\\", "英语资源\\%s\\" % StorybookPathPrefix, audioFilePathColNumCellValue)

结果出错:

    unifiedAudioFilePath = re.sub("英语资源\\", "英语资源\\%s\\" % StorybookPathPrefix, audioFilePathColNumCellValue)

  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 155, in sub

    return _compile(pattern, flags).sub(repl, string, count)

  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 251, in _compile

    raise error, v # invalid expression

sre_constants.error: bogus escape (end of line)

python re.sub sre_constants.error bogus escape end of line

python  sre_constants.error bogus escape end of line

regex – Python re "bogus escape error" – Stack Overflow

加上前缀r,指定为raw string

结果:

unifiedAudioFilePath = re.sub(r"英语资源\\", r"英语资源\\%s\\" % StorybookPathPrefix, audioFilePathColNumCellValue)

然后没有语法错误,可以正常运行了。

不过:结果并没有替换到我们要的。

后来是,加上u表示unicode

unifiedAudioFilePath = re.sub(ur"英语资源\\", ur"英语资源\\%s\\" % StorybookPathPrefix, audioFilePathColNumCellValue)

-》因为此处是Python 2,字符串中间包含中文字符,是unicode的,所以需要指定为unicode。

【总结】

此处,普通的字符串,在正则表达式相关的语法中,

包括

re.sub

re.search

等等,其中的正则部分表示,最后不能包括反斜杠\

如果有,比如我此处的:

英语资源\

就会报错

sre_constants.error bogus escape end of line

解决办法:

加上前缀r,表示是raw string,即可:

unifiedAudioFilePath = re.sub(r"英语资源\\", r"英语资源\\%s\\" % StorybookPathPrefix, audioFilePathColNumCellValue)

另外:

此处,由于是Python 2中,要替换的字符串中包含了unicode的中文字符,所以要加上u,制定为unicode字符串,才能查找并替换掉相应字符:

StorybookPathPrefix = "storybook"

unifiedAudioFilePath = re.sub(ur"英语资源\\", ur"英语资源\\%s\\" % StorybookPathPrefix, audioFilePathColNumCellValue)

转载请注明:在路上 » 【已解决】Python中re.sub出错:sre_constants.error bogus escape end of line

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
92 queries in 0.197 seconds, using 23.34MB memory