簡體   English   中英

在Python中從字符串中刪除不需要的字符

[英]Removing unwanted characters from a string in Python

我有一些字符串,我想從中刪除一些不需要的字符。 例如: Adam'sApple ----> AdamsApple 。(不區分大小寫)有人可以幫助我,我需要最快的方法來做到這一點,因為我有數百萬條記錄需要完善。 謝謝

一個簡單的方法:

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

...或者看看正則表達式替換

將刪除translate方法的第二個參數中的任何字符:

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

注意:translate要求Python 2.6或更高版本對第一個參數使用None,否則必須是長度為256的翻譯字符串。對於2.6之前的版本, string.maketrans ('','')可用於代替None。

這是一個刪除所有惱人的ascii字符的函數,唯一的例外是“&”,用“和”代替。 我用它來監管文件系統並確保所有文件都遵循我堅持每個人都使用的文件命名方案。

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

嘗試:

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

更進一步,用什么都不替換多個字符:

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

產量:

ab
str.replace("'","");

正如現在已多次指出的那樣,你必須使用replace或正則表達式(盡管你很可能不需要正則表達式),但是如果你還必須確保結果字符串是純ASCII(不包含)像é,ò,μ,æ或φ這樣的時髦字符,你終於可以做了

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

一種替代方案,它將接收一個字符串和一組不需要的字符

    # 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

假設我們有以下列表:

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']

我可能遲到的答案,但我認為下面的代碼也會做(到極端)它將刪除所有不道德的字符:

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

哪個會給

'niraj kale 984wywn於2017年2月2日'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM