简体   繁体   中英

Removing a group of specific characters from text (in python)

I wrote this code in python to remove a group of specific characters from texts. But the code works only for the first type of characters, for instance:

"I live in street 223, Los Angeles and this isn't true:)"

should be:

"i live in street los angeles and this isnt true"

but as the number 2 is before the rest of the characters that should be removed -in the set v- the result that I get instead:

"i live in street 3, los angeles and this isn't true:)"

My code:

v = ["1","2","3","4","5","6","7","8","9","0",".","(",")",',',':',";",'"',"'","?","!","+","=","-","$","#","@","<",">"]

def p(r):
   for e in r:
       if e in v:
           return r.replace(e,"")
       else:
           pass
       
print(p("I live in street 223, Los Angeles and this isn't true :)".lower()))

How to modify this code to remove the rest characters? Or is there a better different code? thanks in advance.

Just create a new string without the invalid characters:

chars = {"1","2","3","4","5","6","7","8","9","0",".","(",")",',',':',";",'"',"'","?","!","+","=","-","$","#","@","<",">"}

def replace(s):
    buf = ""
    for c in s:
        if c not in chars:
            buf += c
    return buf

print(replace("I live in street 223, Los Angeles and this isn't true :)"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM