【问题标题】:Removing unwanted characters from a string in Python从 Python 中的字符串中删除不需要的字符
【发布时间】:2011-02-16 09:03:38
【问题描述】:

我有一些字符串,我想从中删除一些不需要的字符。 例如:Adam'sApple ----> AdamsApple.(不区分大小写) 有人可以帮助我吗,我需要最快的方法,因为我有几百万条记录需要完善。 谢谢

【问题讨论】:

  • 您能说得更具体些吗?您要删除哪些确切的字符?

标签: python parsing string


【解决方案1】:

一种简单的方法:

>>> s = "Adam'sApple"
>>> x = s.replace("'", "")
>>> print x
'AdamsApple'

...或查看regex substitutions

【讨论】:

    【解决方案2】:

    这是一个删除所有烦人的ascii字符的函数,唯一的例外是“&”被“and”替换。我用它来监管文件系统,并确保所有文件都遵循我坚持每个人都使用的文件命名方案。

    def cleanString(incomingString):
        newstring = incomingString
        newstring = newstring.replace("!","")
        newstring = newstring.replace("@","")
        newstring = newstring.replace("#","")
        newstring = newstring.replace("$","")
        newstring = newstring.replace("%","")
        newstring = newstring.replace("^","")
        newstring = newstring.replace("&","and")
        newstring = newstring.replace("*","")
        newstring = newstring.replace("(","")
        newstring = newstring.replace(")","")
        newstring = newstring.replace("+","")
        newstring = newstring.replace("=","")
        newstring = newstring.replace("?","")
        newstring = newstring.replace("\'","")
        newstring = newstring.replace("\"","")
        newstring = newstring.replace("{","")
        newstring = newstring.replace("}","")
        newstring = newstring.replace("[","")
        newstring = newstring.replace("]","")
        newstring = newstring.replace("<","")
        newstring = newstring.replace(">","")
        newstring = newstring.replace("~","")
        newstring = newstring.replace("`","")
        newstring = newstring.replace(":","")
        newstring = newstring.replace(";","")
        newstring = newstring.replace("|","")
        newstring = newstring.replace("\\","")
        newstring = newstring.replace("/","")        
        return newstring
    

    【讨论】:

    • 那是在我进入正则表达式之前,基本上相当于我尴尬的哥特阶段的代码。虽然,它确实允许未经培训的人进行修改,这在我的工作中几乎是必需的。
    【解决方案3】:

    translate 方法的第二个参数中的所有字符都被删除:

    >>> "Adam's Apple!".translate(None,"'!")
    'Adams Apple'
    

    注意:translate 需要 Python 2.6 或更高版本才能将 None 用作第一个参数,否则它必须是长度为 256 的翻译字符串。string.maketrans('','') 可以用来代替 None 作为 pre- 2.6 版本。

    【讨论】:

    • 明确提及string.maketrans('', '') 代替None 用于Python 可能会有所帮助
    • "".join(char for char in text if char not in bad_chars) 快六倍 :)
    【解决方案4】:

    试试:

    "Adam'sApple".replace("'", '')
    

    更进一步,用空替换多个字符:

    import re
    print re.sub(r'''['"x]''', '', '''a'"xb''')
    

    产量:

    ab
    

    【讨论】:

      【解决方案5】:
      str.replace("'","");
      

      【讨论】:

        【解决方案6】:

        正如已经多次指出的那样,您必须使用 replace 或正则表达式(但很可能您不需要正则表达式),但如果您还必须确保生成的字符串是纯 ASCII (不包含 é、ò、µ、æ 或 φ 等时髦字符),你终于可以做到了

        >>> u'(like é, ò, µ, æ or φ)'.encode('ascii', 'ignore')
        '(like , , ,  or )'
        

        【讨论】:

          【解决方案7】:

          一个接受字符串和不需要的字符数组的替代方法

              # function that removes unwanted signs from str
              #Pass the string to the function and an array ofunwanted chars
          
          def removeSigns(str,arrayOfChars):
          
              charFound = False
          
              newstr = ""
          
              for letter in str:
                  for char in arrayOfChars:
                      if letter == char:
                          charFound = True
                          break
                  if charFound == False:
                      newstr += letter
                  charFound = False
          
              return newstr
          

          【讨论】:

            【解决方案8】:

            假设我们有以下列表:

            states = [' Alabama ', 'Georgia!', 'Georgia', 'georgia', 'south carolina##', 'West virginia?']
            

            现在我们将定义一个函数clean_strings()

            import re
            
            def clean_strings(strings):
                result = []
                for value in strings:
                    value = value.strip()
                    value = re.sub('[!#?]', '', value)
                    value = value.title()
                    result.append(value)
                return result
            

            当我们调用函数clean_strings(states)

            结果将如下所示:

            ['Alabama',
            'Georgia',
            'Georgia',
            'Georgia',
            'Florida',
            'South Carolina',
            'West Virginia']
            

            【讨论】:

              【解决方案9】:

              我可能迟到了答案,但我认为下面的代码也可以(极端) 它将删除所有不必要的字符:

              a = '; niraj kale 984wywn on 2/2/2017'
              a= re.sub('[^a-zA-Z0-9.?]',' ',a)
              a = a.replace('  ',' ').lstrip().rstrip()
              

              这会给

              'niraj kale 984wywn on 2 2 2017'

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2011-12-24
                • 2011-08-13
                • 2016-06-29
                • 2015-08-06
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多