Sas*_*een 1 python string byte replace python-3.x
I am trying to use Pyner (https://github.com/dat/pyner) for NER. I give it a string of text to extract named entities from it. But I get an error. I am attaching the snipet where the error arises:
for s in ('\f', '\n', '\r', '\t', '\v'): #strip whitespaces
text = text.replace(s, '')
Error message: {TypeError: a bytes-like object is required, not 'str'}
Run Code Online (Sandbox Code Playgroud)
This error occurs even when I try multiple types of inputs (bytes objects)
text = b'This'
text = bytes("This".encode('utf-8'))
Run Code Online (Sandbox Code Playgroud)
I think the problem is that replace is not getting the right input type. I am using python 3.5. What am I doing wrong? Please help!
replace可以混合使用str,bytes但不能同时使用。
你可以像这样重写它:
for s in (b'\f', b'\n', b'\r', b'\t', b'\v'): #strip whitespaces except space!
text = text.replace(s, b'')
Run Code Online (Sandbox Code Playgroud)
您还可以应用strip适用于bytes类型的内容:
text = text.strip() # remove all of the above + space
Run Code Online (Sandbox Code Playgroud)
也可能:转换回str预先,尝试:
text = str(text)
Run Code Online (Sandbox Code Playgroud)
或者
text = text.decode('utf-8')
Run Code Online (Sandbox Code Playgroud)
(选择最佳解决方案以避免修改第三方包,正如帕特里克指出的那样)