【问题标题】:How to replace special characters within a text with a space in Python?如何在 Python 中用空格替换文本中的特殊字符?
【发布时间】:2019-06-01 02:07:38
【问题描述】:

问题说明: 如果发现一个特殊字符用字母表,则用一个空格替换它。而且,如果发现是数字,则直接忽略。

实际情况:

  1. $45
  2. 4.5 inches
  3. Task.This is good.
  4. Hello, How $are you. This is good.

预期场景:

  1. $45
  2. 4.5 inches
  3. Task This is good
  4. Hello How are you This is good

我尝试写 one regex 来找出遵循这种模式的文本,但不确定如何用空格替换该文本中的特殊字符。

例如在上图中,预期输出为'ddddd dfhghg''222 d' 等。

这种情况可以用 re.sub(pattern, replacement, input) 处理吗?如果是,请告诉如何:)

【问题讨论】:

    标签: python regex python-3.x


    【解决方案1】:

    您可以使用带有否定外观的字符集:

    (?<!\d)([.,$])(?!\d) 
    

    将所有应该替换的字符放在括号内:[.,$]

    Demo

    解释:

    • (?&lt;!\d)negative lookbehind - 确保在匹配字符之前没有数字
    • (?!\d)negative 前瞻 - 确保匹配字符后没有数字
    • [...] 包含您要替换的所有特殊字符的字符集

    【讨论】:

    • 宾果游戏!这正是我一直在寻找的。非常感谢@mrzasa
    • 还有一个问题:我真正想要的是在捕获组中考虑除空格之外的所有特殊字符,并且正在这样做 pat = re.compile(r"(??@[]^_`{|}~])(?!\d)") print(pat.sub(" \ \1 ", text)) 这种模式(pat)可以进一步优化吗?
    • 我觉得还可以
    【解决方案2】:

    我会按照这些思路尝试一些东西,这在性能上肯定不是最理想的,但很实用

    class Replacer
        def __init__(self, special_chars):
            self.special_chars = special_chars
    
        def replace(self, s):
            for ch in self.special_chars:
                for match in re.finditer(ch, s):
                    if not is_followed_by_numbers(s, match.start())
                        s = replace_at_index(s, match.start())
    
        def is_followed_by_numbers(self, s, start):
            pass # Provide your implementation
    
        def replace_at_index(self, s, index):
            pass # Provide your implementation
    

    【讨论】:

    • 感谢 Jorge 回答问题。提供的答案 mrzasa 更加清晰明了,因此我接受了这个答案。再次感谢您为我的问题提供解决方案:)
    猜你喜欢
    • 2013-11-03
    • 1970-01-01
    • 1970-01-01
    • 2013-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多