【问题标题】:python: cleaning up a stringpython:清理字符串
【发布时间】:2010-09-01 19:07:26
【问题描述】:

我有一个这样的字符串

somestring='in this/ string / i have many. interesting.occurrences of {different chars} that need     to .be removed  '

这是我想要的结果:

somestring='in this string i have many interesting occurrences of different chars that need to be removed'

我开始手动做各种.replace,但是有这么多不同的组合,我认为必须有更简单的方法。也许有一个图书馆已经这样做了?

有谁知道我如何清理这个字符串>?

【问题讨论】:

    标签: python string


    【解决方案1】:

    我会使用正则表达式将所有非字母数字替换为空格:

    >>> import re
    >>> somestring='in this/ string / i have many. interesting.occurrences of {different chars} that need     to .be removed  '
    >>> rx = re.compile('\W+')
    >>> res = rx.sub(' ', somestring).strip()
    >>> res
    'in this string i have many interesting occurrences of different chars that need to be removed'
    

    【讨论】:

    【解决方案2】:

    您有两个步骤:删除标点符号,然后删除多余的空格。

    1) 使用 string.translate

    import string
    trans_table = string.maketrans( string.punctuation, " "*len(string.punctuation)
    new_string = some_string.translate(trans_table)
    

    然后应用一个将标点符号映射到空格的转换表。

    2) 去除多余的空格

    new_string = " ".join(new_string.split())
    

    【讨论】:

      【解决方案3】:
      re.sub('[\[\]/{}.,]+', '', somestring)
      

      【讨论】:

      • 注意interesting.occurrences需要变成interesting occurrences并加空格。
      • 并将多个空格'need      to'压缩为一个'need to'
      猜你喜欢
      • 2010-10-30
      • 2011-06-22
      • 2011-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-29
      • 2022-01-06
      • 2010-11-17
      相关资源
      最近更新 更多