简体   繁体   English

使用 re.sub 删除字符

[英]Remove characters using re.sub

I'm trying to remove the special characters with the re.sub() function, but when I use the re.sub() function my replace function stops working.我正在尝试使用re.sub() function 删除特殊字符,但是当我使用re.sub() function 时,我的替换 function 停止工作。

Excel,导入

My code: import re import pandas as pd from IPython.display import display我的代码: import re import pandas as pd from IPython.display import display

tabela = pd.read_excel("tst.xlsx")
(tabela[['nome', 'mensagem', 'arquivo', 'telefone']]) 

for linha in tabela.index:
    nome = tabela.loc[linha, "nome"]
    mensagem = tabela.loc[linha, "mensagem"]
    acordo = tabela.loc[linha, "acordo"]
    telefone = tabela.loc[linha, "telefone"]

    texto = mensagem.replace("fulano", nome)
    texto = texto.replace( "value", acordo)
    texto = texto.replace( "phone", telefone)
    texto = re.sub(r"[!!@#$%¨&*()_?',;.]", '', telefone)
    print(texto)

Print result:打印结果:

11

How it should come out:它应该如何出来:

thyago

R$200

11

Loops should be rarely used in Pandas. Try this:在 Pandas 中应该很少使用循环。试试这个:

tabela['telefone'] = tabela['telefone'].str.replace(r'[!!@#$%¨&*()_?\',;.]', '', regex=True)    
tabela['mensagem']= tabela.apply(lambda x: x['mensagem'].replace('fulano', str(x['nome'])), axis=1)
tabela['mensagem']= tabela.apply(lambda x: x['mensagem'].replace('value', str(x['acordo'])), axis=1)
tabela['mensagem']= tabela.apply(lambda x: x['mensagem'].replace('phone', str(x['telefone'])), axis=1)

Try this:尝试这个:

repalce更换

texto = re.sub(r"[!!@#$%¨&*()_?',;.]", '', telefone)

to

texto = re.sub(r"[!!@#$%¨&*()_?',;.]", '', texto)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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