首页 > 解决方案 > Python使用正则表达式删除文本中的标点符号

问题描述

我正在使用 Json 文件,特别是“上下文”下的文本(参见代码)。

正如您在代码中看到的那样,我使用 3 个 while 循环来处理其中的 3 个情况。我想知道是否有更好的方法来实现这一点。

]['content'] = trans
            segments.append(jsondata[i])
    jsondata = segments

另外我想知道是否有办法删除双空格并使其成为一个空格。

标签: pythonregex

解决方案


很可能我们想要一个表达式传递除了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.

推荐阅读