gpt4 book ai didi

python - 使用正则表达式删除特殊的 Unicode 字符?

转载 作者:太空宇宙 更新时间:2023-11-03 15:51:56 25 4
gpt4 key购买 nike

我正在使用维基百科的 API 来获取一个简单的 JSON 对象,其中包含 wiki 页面的第一段,稍后我想使用文本转语音将其读给用户。然而,有些文章有正确发音的特殊转录。例如,当我点击 Chihuahua 的链接时JSON 中的文本如下所示:“The Chihuahua/t\u0283\u026a\u02c8w\u0251\u02d0w\u0251\u02d0/(西类牙语:chihuahue\u00f1o)是最小的狗品种” 我的问题是,删除发音部分的正则表达式是什么(并且可能删除任何 Unicode 特殊字符:\u 和之后的 4 个字符)?

尝试 re.sub("\/.+\/", "", test) 只是在彼此后面添加另一个 \ \ >.

最佳答案

(假设现在您正在使用 Python,因为您使用了 re.sub ,并且您只想删除 /tʃɪˈwɑːwɑː/ 因为您的示例正则表达式。)

首先,您需要对正则表达式模式使用 Python 的原始字符串表示法,因为 Python 对其他内容使用反斜杠 ( source );在正则表达式的字符串文字前面放置一个 r ,您的原始示例可能就足够了。

无论如何,您的方向是正确的 - Unicode 不需要对此处的示例进行任何特殊处理。您只需删除两个斜杠之间的所有内容即可。我还会限制斜杠之间的匹配空格,这样您就不会捕获文档中相距较远的两个单斜杠之间的所有内容。以下内容在 Python 2.7.12 REPL 中对我有用:

>>> re.sub(r'\/[^/\s]+\/\s*', '', "The Chihuahua /t\u0283\u026a\u02c8w\u0251\u02d0w\u0251\u02d0/ (Spanish: chihuahue\u00f1o) is the smallest breed of dog")
'The Chihuahua (Spanish: chihuahue\\u00f1o) is the smallest breed of dog'

这是正则表达式的分解:

\/    # Match opening slash on the pronunciation expression
[^ # Begin a negated character set
/ # Exclude the forward-slash /
\s # Also exclude all whitespace
]+ # Match one or more character that is not a slash or whitespace
\/ # Match closing slash on the pronunciation expression
\s* # Capture any whitespace that follows, too

关于python - 使用正则表达式删除特殊的 Unicode 字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41201101/

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