Python字符串替换不起作用(需要输入字节吗?) [英] Python string replace not working (bytes input expected?)

查看:67
本文介绍了Python字符串替换不起作用(需要输入字节吗?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Pyner( https://github.com/dat/pyner )对于NER.我给它一个文本字符串,以从中提取命名实体.但是我得到一个错误.我在发生错误的地方附上了摘要:

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'}

即使我尝试多种类型的输入(字节对象),也会发生此错误

This error occurs even when I try multiple types of inputs (bytes objects)

text = b'This'
text = bytes("This".encode('utf-8'))

我认为问题是替换没有得到正确的输入类型.我正在使用python 3.5.我究竟做错了什么?请帮忙!

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 一起使用,但不能同时使用.

replace works with str or bytes but not both mixed.

您可以这样重写它:

for s in (b'\f', b'\n', b'\r', b'\t', b'\v'): #strip whitespaces except space!
    text = text.replace(s, b'')

您还可以应用与 bytes 类型一起使用的 strip :

you could also to apply strip which works with bytes type:

text = text.strip()  # remove all of the above + space

也可以:尝试先转换回 str

Also possible: convert back to str beforehand, trying:

text = str(text)

text = text.decode('utf-8')

(如Patrick所言,选择最佳的解决方案以避免修改第三方程序包)

(choose the best solution to avoid modifying a third-party package, as Patrick noted)

这篇关于Python字符串替换不起作用(需要输入字节吗?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆