不能在类似字节的对象上使用字符串模式 - python的重新错误

时间:2015-05-27 09:43:54

标签: python regex

我正在进行python挑战并尝试熟悉python,所以在没有查看答案的情况下,我尝试使用python的url阅读器来阅读html,然后找到所需的字母。但是在下面的代码中我得到一个错误,最初是python 3 urllib.request但是在解决之后我得到一个新的错误:

<module>
    print ("".join(re.findall("[A-Za-z]", data)))
  File "C:\Python34\lib\re.py", line 210, in findall
    return _compile(pattern, flags).findall(string)
TypeError: can't use a string pattern on a bytes-like object

现在我尝试在google上查看此错误,但我得到的只是关于json,我不应该这样做?我的python不是那么强大,所以也许我这样做不正确?

#Question 2 - find rare characters

import re
import urllib.request

data = urllib.request.urlopen("http://www.pythonchallenge.com/pc/def/ocr.html")
mess = data.read()
messarr = mess.split("--")

print ("".join(re.findall("[A-Za-z]", data)))

#Question 3 - Find characters in list

page = urllib.request.urlopen("http://www.pythonchallenge.com/pc/def/equality.html")
mess = page.read()
messarr = mess.split("--")
print ("".join(re.findall("[^A-Z]+[A-Z]{3}([a-z])[A-Z]{3}[^A-Z]+", page)))

1 个答案:

答案 0 :(得分:13)

问题是你要混合字节和文本字符串。您应该将数据解码为文本字符串(unicode),例如data.decode('utf-8'),或使用字节对象作为模式,例如re.findall(b"[A-Za-z]")(请注意字符串文字前面的前导b。)