我正在尝试用''替换我自己的自定义字符。以下是我感到困惑的地方:
如果我只替换一个字符,就可以了:
a=pd.DataFrame({'title':['a/b','a # b','a+b']})
a.loc[:,'title1']=a.loc[:,'title'].astype(str).str.replace('/',' ')
a
结果是:
title title1
0 a/b a b
1 a # b a # b
2 a+b a+b
如果我使用包含一些字符的短字符串,也可以:
b2='[?|:|-|'|\|/]'
a=pd.DataFrame({'title':['a/b','a # b','a+b']})
a.loc[:,'title1']=a.loc[:,'title'].astype(str).str.replace(b2,' ')
a
结果是:
title title1
0 a/b a b
1 a # b a # b
2 a+b a+b
但是,当我尝试使用长字符串来执行此操作时,没有任何变化:
b1='[?|:|-|'|\|.|(|)|[|]|{|}|/]'
a=pd.DataFrame({'title':['a/b','a # b','a+b']})
a.loc[:,'title1']=a.loc[:,'title'].astype(str).str.replace(b1,' ')
a
结果是:
title title1
0 a/b a/b
1 a # b a # b
2 a+b a+b
您可以看到,在前两个示例中,/被替换为 ' '。但是在最后一个中,更换没有发生,我不知道为什么?这是因为字符串有限制吗?或者,有我不知道的更好的方法?
更新
非常感谢@Oliver郝。但是我该如何对数据框中的一列(或多列(执行此操作,然后将结果作为新列保存回数据框。所以当我尝试时:
regex = r"[?:-'\|.()[]{}/]"
a.loc[:,'title1']=re.sub(regex," ",a.loc[:,'title'],0,re.MULTILINE)
我收到错误:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:UsersfefechenAppDataLocalProgramsPythonPython37libre.py", line 192, in sub
return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or bytes-like object
这个表达式也可能有效,
b1="[|,.:;+–_#&@!$%()[]{}?'"/\-]"
逃逸次数少。
更新至:b1='[?:-'\|.()[]{}/]'
正则表达式演示
法典:
# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"[?:-'\|.()[]{}/]"
test_str = "'a/b','a # b','a+b'"
subst = " "
# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)
if result:
print (result)
# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
我自己找到了答案。最后一个不起作用,因为我应该这样做:
b1="[?|:|-|–|'|\|.|(|)|[|]|{|}|/|#|+|,|;|_|"|&|@|!|$|%||]"
将 \ 放在一些特殊字符的前面。