为什么这个代码一直抛出这个错误?TypeError:不能在byteslike对象上使用字符串模式

2024-04-30 05:47:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码引发以下错误:

defs = LI_re.findall(text)
TypeError: cannot use a string pattern on a bytes-like object    

所以这里是我的代码,我用它来清理从字典网站上提取的信息。你知道吗

任何帮助都将不胜感激。你知道吗

clean_defs = []
LI_re = re.compile(r'<LI>(.*)</LI>') 
HTML_re = re.compile(r'<[^>]+>\s*')
defs = LI_re.findall(text) # THE ERROR HAPPENS HERE
# remove internal tags                                                                                      
for d in defs:
    clean_d = HTML_re.sub('',d)
    if clean_d: clean_defs.append(clean_d)

return clean_defs #My return from the function or whatever

Tags: 代码textrecleanstringreturnusehtml
1条回答
网友
1楼 · 发布于 2024-04-30 05:47:25

text显然是字节对象。有几种解决办法。可以将text更改为字符串:

text = text.decode()

这将给出字符串(str)结果。你知道吗

或者将正则表达式更改为使用字节对象:

LI_re = re.compile(br'<LI>(.*)</LI>')
HTML_re = re.compile(br'<[^>]+>\s*')

这将给出byte对象结果。你知道吗

相关问题 更多 >