python - Python使用正则表达式删除文本中的标点符号
问题描述
我正在使用 Json 文件,特别是“上下文”下的文本(参见代码)。
正如您在代码中看到的那样,我使用 3 个 while 循环来处理其中的 3 个情况。我想知道是否有更好的方法来实现这一点。
]['content'] = trans
segments.append(jsondata[i])
jsondata = segments
另外我想知道是否有办法删除双空格并使其成为一个空格。
解决方案
很可能我们想要一个表达式传递除了space后面的标点符号列表和换行符之外的所有内容。
也许,让我们从:
([\s\S].*?)(\s,|\s\.|\s!|\s\?|\s;|\s:|\s\|)?
我们可以有两个捕获组。第一个传递所有内容,第二个排除由逻辑 OR 分隔的实例列表,如果我们愿意,也可以简化。
正则表达式
如果不需要此表达式,可以在regex101.com中对其进行修改或更改。
正则表达式电路
jex.im还有助于可视化表达式。
演示
这个片段只是为了表明表达式可能是有效的:
const regex = /([\s\S].*?)(\s,|\s\.|\s!|\s\?|\s;|\s:|\s\|)?/gm;
const str = `Start with some text Hello ? World ! Hello , World . Hello ; World | Hello : Hello? World! Hello, World. Hello; World| Hello:Hello ? World ! Hello , World . Hello ; World | Hello : Hello? World! Hello, World. Hello; World| Hello: and some other text after`;
const subst = `$1`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
Python 测试
# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"([\s\S].*?)(\s,|\s\.|\s!|\s\?|\s;|\s:|\s\|)?"
test_str = "Start with some text Hello ? World ! Hello , World . Hello ; World | Hello : Hello? World! Hello, World. Hello; World| Hello:Hello ? World ! Hello , World . Hello ; World | Hello : Hello? World! Hello, World. Hello; World| Hello: and some other text after"
subst = "\\1"
# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)
if result:
print (result)
# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
推荐阅读
- java - 我想使用不同的用户名和密码从不同的浏览器登录到应用程序
- javascript - 无法在 jsfiddle 上复制这种水平视差效果
- c# - 无法将字符串转换为日期时间
- swift - 为什么我不能在 Swift 中将 (String) -> String 转换为 (Any) -> Any?
- python - 为什么不能在 for 循环中操作“i”
- azure - 是否有用于识别上位 CPU/内存使用进程的日志
- mysql - 如何在 dolphindb 中创建视图?
- matlab - 我如何将每个观察的概率分布绘制为彩色图?
- php - 在命令行中使用 curl 通过 JSON 对象发布数据
- jenkins - 如何通过在 jenkins 脚本控制台上编写 groovy 脚本来获取环境变量的值?