从文本中删除一组特定字符(在 python 中)
Removing a group of specific characters from text (in python)
我在 python 中编写了这段代码,用于从文本中删除一组特定字符。但该代码仅适用于第一类字符,例如:
“我住在洛杉矶 223 号街道,这不是真的:)”
应该是:
“我住在洛杉矶街头,这不是真的”
但是由于数字 2 在应该删除的其余字符之前 - 在集合 v 中 - 我得到的结果是:
“我住在洛杉矶 3 号街,这不是真的:)”
我的代码:
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()))
如何修改此代码以删除其余字符?
或者有更好的不同代码吗?
提前致谢。
只需创建一个不含无效字符的新字符串:
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 :)"))
我在 python 中编写了这段代码,用于从文本中删除一组特定字符。但该代码仅适用于第一类字符,例如:
“我住在洛杉矶 223 号街道,这不是真的:)”
应该是:
“我住在洛杉矶街头,这不是真的”
但是由于数字 2 在应该删除的其余字符之前 - 在集合 v 中 - 我得到的结果是:
“我住在洛杉矶 3 号街,这不是真的:)”
我的代码:
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()))
如何修改此代码以删除其余字符? 或者有更好的不同代码吗? 提前致谢。
只需创建一个不含无效字符的新字符串:
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 :)"))